Singletons & more

The Limitations of Static Variables

To start with the basics, a static variable looks like this:

public class SomeClassObject : MonoBehaviour {
    public static bool someStaticBoolFlag = false;
    public bool someLocalBool = true;
}

With this code, you could use SomeClassObject.someStaticBoolFlag to access that variable from anywhere. Moreover, this points to a single, shared bool that exists exactly once in your entire game. On the other hand, every copy of SomeClassObject will have its own someLocalBool, and someLocalBool is visible in the Inspector.

What if you want a variable that is visible and editable in the inspector, but you only want there to be one of them, and you want it accessible from everywhere? You might be looking for a singleton. To put it simply, a singleton is a static reference to an object of that same type, and generally, there is only one of them in the scene. In its simplest form, it looks something like this:

public class SomeClassObject : MonoBehaviour {
    public static SomeClassObject instance;
    public bool someLocalBool = true;

    void Awake() {
        instance = this;
    }
}

Now, in any script file, you can use the code SomeClassObject.instance.someLocalBool = false; to access that local bool on the object, and you can modify this bool in the object's inspector, as well. Success!

Words of Warning

"That seems amazing and really simple," I head you saying through the screen. "Why would I not want to use these everywhere?" Well, you know what, you might want to. But the truth is that you shouldn't. Many people are hesitant to teach newbies about singletons because they're like code candy - they're simple, they're quick, they're easy, but in the long run, too many of them can be bad for your project.

results for ""

    No results matching ""