我修改单例以便它只适用于scene
,我也删除了DontDestroyOnLoad()并将_instance重置为null。
但问题是,这个新的单身GameObject被放置在其他场景中。所以当场景卸载时,它不会破坏,因为它在其他场景上。
SingletonScene
应位于Kanga1
的相应场景中。
public class SingletonScene<T> : MonoBehaviour where T : MonoBehaviour
{
private static T _instance;
private static object _lock = new object();
public static T instance
{
get
{
lock (_lock)
{
if (_instance == null)
{
_instance = (T)FindObjectOfType(typeof(T));
if (FindObjectsOfType(typeof(T)).Length > 1)
{
Debug.LogError("[Singleton] Something went really wrong " +
" - there should never be more than 1 singleton!" +
" Reopening the scene might fix it.");
return _instance;
}
if (_instance == null)
{
GameObject singleton = new GameObject();
_instance = singleton.AddComponent<T>();
singleton.name = "(SingletonScene) " + typeof(T).ToString();
Debug.Log("[SingletonScene] An instance of " + typeof(T) +
" is needed in the scene, so '" + singleton +
"' was created");
}
else
{
Debug.Log("[Error] this should not happen on SingletonScene " +
_instance.gameObject.name);
}
}
return _instance;
}
}
}
public void OnDestroy()
{
_instance = null;
}
}