Trying to understand singleton pattern

Is being a amazing course thanks. But I found my self a little confused about the use of statics and the singleton.

I can not found why should be different the use of the UnitActionSystem instance than MouseWorld instance. Why is treated different?

Also, I guess that using the public static class instance you avoid to have to find them on the scene, correct?

Technically speaking, our MouseWorld instance should be checked for duplicates in the same manner as the UnitActionSystem. Not necessarily in exposing the instance to the public (you don’t need to expose it to the public because the method we call is static) but in how we manage multiple instances.

The static keyword indicates that the variable, property or method is tied to the class, and not to the instance of the class. This means you don’t need a handle on an instance to call the variable, property, or method to use it.

The Singleton takes advantage of this principle to keep track of exactly ONE instance of a class. By using a Singleton, we don’t have to use expensive methods like FindObjectOfType to get to the class.

The classic construction of a Singleton involves a static instance variable and a trap in Awake to initialize the instance and ensure that there can be only one of the Singletons:

    private void Awake()
    {
        if (Instance != null) //If this is a second copy of the class, then we want to destroy it
        {
            Debug.LogError("There's more than one UnitActionSystem! " + transform + " - " + Instance);
            Destroy(gameObject);
            return;
        }
        Instance = this; //Now instance can be referenced with UnitActionSystem.instance 
        ///just as if we'd located the UnitActionSystem with FindObjectOfType<UnitActionSystem>()
    }
2 Likes

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms