Skip to content

Instantly share code, notes, and snippets.

@yangruihan
Last active February 15, 2019 08:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yangruihan/4d8a47f0bd15bbd5f2000b3dc0bd7459 to your computer and use it in GitHub Desktop.
Save yangruihan/4d8a47f0bd15bbd5f2000b3dc0bd7459 to your computer and use it in GitHub Desktop.
MonoBehaviour 单例
using UnityEngine;
/// <summary>
/// extends this class to become singleton class.
/// </summary>
/// <typeparam name="T"> T is a SingletonMono class </typeparam>
public class SingletonMono<T> : MonoBehaviour where T : SingletonMono<T>
{
private static T _instance;
public static T Instance
{
get
{
if (_instance == null)
_instance = FindObjectOfType<T>();
if (_instance != null) return _instance;
var go = new GameObject(typeof(T) + "_Singleton");
_instance = go.AddComponent<T>();
DontDestroyOnLoad(go);
return _instance;
}
}
public static T GetMonoInstance()
{
if (_instance == null)
{
if (Application.isPlaying)
{
var go = new GameObject(typeof(T).Name);
_instance = go.AddComponent<T>();
DontDestroyOnLoad(go);
}
}
return _instance;
}
protected virtual void Awake()
{
if (_instance == null)
_instance = this as T;
}
public virtual void Init()
{
}
public void Free()
{
FreeSingleton();
_instance = null;
Destroy(gameObject);
}
protected virtual void FreeSingleton()
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment