Last active
April 8, 2019 07:47
-
-
Save TouiSoraHe/a9bb2c41036125e1719d246b31f6793c to your computer and use it in GitHub Desktop.
适用于Unity的单例类,继承自MonoBehaviour,具备MonoBehaviour特性
This file contains hidden or 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; | |
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