Exportation of singletons fields (C#)

Godot Version

4.4.1

Question

Hi, I've been programming with Godot in C# language for a mounth and I've a problem with singletons (autoloads). I've created a class called "Global" associated to a simple node and I've put inside it some fields like, for example, scrolling speed (it's a flappy bird game). The probleme here is that when I export this field and try modificate it in the inspector, it's like it wasn't modificated. Do you know why it doesn't work? I'm sorry if I did some mistakes but I'm italian and this is my first post on a forum.

You’re not supposed to export a Singleton if done right. A singleton should be accessible anywhere, and will contain the same data no matter what, since there can, and SHOULD only have a single instance of it.
Generally, you’d set up a singleton like this:

public partial class YourSingletonClass : Node
{
    public static YourSingletonClass Instance;

    public override void _Ready()
    {
        base._Ready();
        Instance ??= this;
    }
}

And anywhere else in your code, you can simply access it like so:

YourSingletonClass.Instance.SomeFunction();

You should not try to export this class. Simply include it in your Autoload and use it as shown above!

1 Like

I tried to export a field, not the istance. Can I do that? If no, how can I put in my code variables that are accessible to every class and editable in the inspector?

I wouldn’t try to put any exported properties in a Singleton, unless it’s part of this same singleton. Instead, use Events, and subsribe to said events from any other class that needs to change based on some action that the Singleton handles. With Events you can also pass any data you wish, see: