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?