Last active
February 15, 2019 08:15
-
-
Save yangruihan/4d8a47f0bd15bbd5f2000b3dc0bd7459 to your computer and use it in GitHub Desktop.
MonoBehaviour 单例
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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