Title: InvalidOperationException When Using RuntimeInitializeOnLoadMethod in Build Version

Question:

I am trying to create a singleton object that is automatically instantiated. Below is the code I have written:

public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
    private static T _instance;

    public static T Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = (T)FindObjectOfType(typeof(T));

                if (_instance == null)
                {
                    GameObject obj = new GameObject(typeof(T).Name, typeof(T));
                    _instance = obj.GetComponent<T>();
                }
            }

            return _instance;
        }
    }

    protected virtual void Awake()
    {
        if (transform.parent != null && transform.root != null)
        {
            DontDestroyOnLoad(this.transform.root.gameObject);
        }
        else
        {
            DontDestroyOnLoad(this.gameObject);
        }
    
        var findedObjects = FindObjectsByType<T>(FindObjectsSortMode.None);
        if (findedObjects.Length > 1)
        {
            Destroy(gameObject);
        }
    }
 
    [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)]
    private static void Initialize()
    {
        SelfInstantiate();
    }
 
    private static void SelfInstantiate()
    {
        if (_instance == null)
        {
            GameObject obj = new GameObject(typeof(T).Name, typeof(T));
            _instance = obj.GetComponent<T>();
        }
    }
}

However, I encounter the following error in the build version:

InvalidOperationException: Could not execute the method because the containing type 'Singleton`1[T]' is not fully instantiated.

I have tried using both RuntimeInitializeLoadType.BeforeSceneLoad and RuntimeInitializeLoadType.AfterSceneLoad, but the error persists.

What I have tried:

• Attempted to initialize the singleton with both RuntimeInitializeLoadType.BeforeSceneLoad and RuntimeInitializeLoadType.AfterSceneLoad.

• Verified the code works without errors in the Unity Editor.

Question:

What is causing this error in the build version, and how can I resolve it?

Rather than have it self-instantiate via RuntimeInitializeOnLoadMethod, have it self-instantiate when it’s first accessed.

Also, does this need to be a monobehaviour?

Feel free to use my MonoSingleton. This has all kinks worked out AND you can use it both ways, either it instantiates a gameobject and adds itself to it when first accessing the Singleton instance, or you can add it as a component to a game object and it will use that instance.

In both cases the singleton resides in DontDestroyOnLoad and prevents duplication or deliberate / accidental Destroy because a singleton’s lifetime should only end when the application quits. This may seem a little restrictive but it helps to prevent common issues.