Well, firstly will say that I check a few similar threads but still cannot figure it out what I am doing wrong!
I am not pro dev, so yeah, probably I am not getting the idea very clearly but still trying.
The error:
DontDestroyOnLoad only work for root GameObjects or components on root GameObjects.
UnityEngine.Object:smile:ontDestroyOnLoad(Object)
Singleton`1:Awake() (at Assets/Scripts/Singleton.cs:31)
The error comes from:
DontDestroyOnLoad(gameObject);
Here is my code:
using UnityEngine;
public class Singleton<T> : MonoBehaviour where T: MonoBehaviour
{
private static T instance;
public static T Instance
{
get
{
if (instance == null)
{
instance = GameObject.FindObjectOfType<T>();
if (instance == null)
{
GameObject singleton = new GameObject(typeof(T).Name);
instance = singleton.AddComponent<T>();
}
}
return instance;
}
}
public virtual void Awake()
{
if (instance == null)
{
instance = this as T;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
}
}
One more thing, Visual studio (mac version) shows me this hint:
Should I change it from GameObject just to Object?


