Static monobehaviours

Hi guys,

Just wondering how I can make a derivable monobehaviour class.

If I do it like below, when i derive from it, my derived class won’t see any of it’s own functions because instance returns the base class not the derived class. What keyword should I be using instead of StaticMonoBehaviour here:

public static StaticMonoBehaviour instance;

Thanks,
Primoz

public class StaticMonoBehaviour : MonoBehaviour
{
    public static StaticMonoBehaviour instance;

    private void Awake()
    {
        if (instance == null)
        {
            instance = this;
        }
        else if (instance != this)
        {
            Destroy(gameObject);
        }
    }
}

This is a singleton pattern. That means there is one of the object in the game. It doesn’t really make sense to have this somehow be dynamic for child classes… which one would it return??

Just duplicate the singleton pattern on each subclass to get the singleton for that subclass.

If you don’t want to duplicate the singleton code, try using the generic Singleton base class from this article as your base class: https://wiki.unity3d.com/index.php/Singleton. But note you’ll still need to access the instance for each subclass by using its own static Instance property, not the one from the base class.

Thank you that singleton script does the trick