83 lines
2.1 KiB
C#
83 lines
2.1 KiB
C#
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
|
|
public class MonoSingleton<T> : MonoBehaviour where T : MonoBehaviour
|
|
{
|
|
private static T instance;
|
|
private static object locker = new object();
|
|
|
|
// public static T Instance
|
|
// {
|
|
// get
|
|
// {
|
|
// return instance;
|
|
// }
|
|
// }
|
|
|
|
public static T Instance
|
|
{
|
|
get
|
|
{
|
|
if (instance == null)
|
|
{
|
|
lock (locker)
|
|
{
|
|
instance = FindObjectOfType<T>();
|
|
if (FindObjectsOfType<T>().Length > 1)
|
|
{
|
|
#if UNITY_EDITOR
|
|
Debug.LogError($"{typeof(T)} ²»Ó¦¸Ã´æÔÚ¶à¸öµ¥Àý£¡");
|
|
#endif
|
|
return instance;
|
|
}
|
|
|
|
if (instance == null && Application.isPlaying)
|
|
{
|
|
var singleton = new GameObject();
|
|
instance = singleton.AddComponent<T>();
|
|
singleton.name = "(singleton)_" + typeof(T);
|
|
// singleton.hideFlags = HideFlags.None;
|
|
// DontDestroyOnLoad(singleton);
|
|
}
|
|
else
|
|
{
|
|
// DontDestroyOnLoad(instance.gameObject);
|
|
}
|
|
}
|
|
// instance.hideFlags = HideFlags.None;
|
|
}
|
|
|
|
return instance;
|
|
}
|
|
}
|
|
|
|
// public static bool IsInitialized
|
|
// {
|
|
// get
|
|
// {
|
|
// return instance != null;
|
|
// }
|
|
// }
|
|
|
|
// public virtual void Awake()
|
|
// {
|
|
// if (instance != null)
|
|
// {
|
|
// Debug.LogErrorFormat("Trying to instantiate a second instance of singleton class {0}", GetType().Name);
|
|
// }
|
|
// else
|
|
// {
|
|
// instance = (T)this;
|
|
// }
|
|
// }
|
|
|
|
// public virtual void OnDestroy()
|
|
// {
|
|
// if (instance == this)
|
|
// {
|
|
// instance = null;
|
|
// }
|
|
// }
|
|
}
|