Skip to content

Instantly share code, notes, and snippets.

@TouiSoraHe
Last active April 8, 2019 07:47
Show Gist options
  • Save TouiSoraHe/a9bb2c41036125e1719d246b31f6793c to your computer and use it in GitHub Desktop.
Save TouiSoraHe/a9bb2c41036125e1719d246b31f6793c to your computer and use it in GitHub Desktop.
适用于Unity的单例类,继承自MonoBehaviour,具备MonoBehaviour特性
using UnityEngine;
public class SingletonMB<T> : MonoBehaviour where T : SingletonMB<T>
{
private static T Instance;
public static T GetInstance()
{
if (Instance == null)
{
Instance = FindObjectOfType<T>();
if(Instance == null)
{
GameObject go = new GameObject(typeof(T).Name);
Instance = go.AddComponent<T>();
}
}
return Instance;
}
protected virtual void Awake()
{
if (Instance != null)
{
if (Instance != this)
{
Debug.LogErrorFormat("试图实例化第二个单例类: {0}", GetType().Name);
Destroy(gameObject);
return;
}
}
else
{
Instance = (T)this;
}
}
protected virtual void OnDestroy()
{
if (Instance == this)
{
Instance = null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment