81 lines
2.5 KiB
C#
81 lines
2.5 KiB
C#
using UnityEngine;
|
|
|
|
namespace SolarEngine.Singleton
|
|
{
|
|
public class SingletonMonoBehaviour<T> : MonoBehaviour where T : SingletonMonoBehaviour<T>
|
|
{
|
|
public static T Instance
|
|
{
|
|
get
|
|
{
|
|
return SingletonMonoBehaviour<T>.CreateInstance();
|
|
}
|
|
}
|
|
|
|
public static T CreateInstance()
|
|
{
|
|
if (SingletonMonoBehaviour<T>.instance == null)
|
|
{
|
|
SingletonMonoBehaviour<T>.instance = (T)((object)UnityEngine.Object.FindObjectOfType(typeof(T)));
|
|
if (SingletonMonoBehaviour<T>.instance == null)
|
|
{
|
|
string name = typeof(T).Name;
|
|
UnityEngine.Debug.LogFormat("Create singleton object: {0}", new object[]
|
|
{
|
|
name
|
|
});
|
|
GameObject gameObject = new GameObject(name);
|
|
Object.DontDestroyOnLoad(gameObject);
|
|
SingletonMonoBehaviour<T>.instance = gameObject.AddComponent<T>();
|
|
if (SingletonMonoBehaviour<T>.instance == null)
|
|
{
|
|
UnityEngine.Debug.LogWarning("Can't find singleton object: " + typeof(T).Name);
|
|
UnityEngine.Debug.LogError("Can't create singleton object: " + typeof(T).Name);
|
|
return (T)((object)null);
|
|
}
|
|
}
|
|
}
|
|
return SingletonMonoBehaviour<T>.instance;
|
|
}
|
|
|
|
public static bool IsInstantiated()
|
|
{
|
|
return SingletonMonoBehaviour<T>.instance != null;
|
|
}
|
|
|
|
protected void Awake()
|
|
{
|
|
if (this.CheckInstance())
|
|
{
|
|
this.AwakeValidly();
|
|
}
|
|
}
|
|
|
|
protected virtual void AwakeValidly()
|
|
{
|
|
}
|
|
|
|
private bool CheckInstance()
|
|
{
|
|
if (SingletonMonoBehaviour<T>.instance == null)
|
|
{
|
|
SingletonMonoBehaviour<T>.instance = (T)((object)this);
|
|
DontDestroyOnLoad(this.gameObject);
|
|
return true;
|
|
}
|
|
if (SingletonMonoBehaviour<T>.Instance == this)
|
|
{
|
|
return true;
|
|
}
|
|
UnityEngine.Object.Destroy(this);
|
|
return false;
|
|
}
|
|
|
|
protected void DontDestroyOnLoad()
|
|
{
|
|
UnityEngine.Object.DontDestroyOnLoad(base.gameObject);
|
|
}
|
|
|
|
private static T instance;
|
|
}
|
|
} |