Last active
October 6, 2019 07:36
-
-
Save sunny352/3e168d85d070829b45f1caedf389a67d to your computer and use it in GitHub Desktop.
Unity中的单例模板
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; | |
namespace Utils | |
{ | |
public class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T> | |
{ | |
public static T Inst | |
{ | |
get | |
{ | |
CreateInst(); | |
return _inst; | |
} | |
} | |
public static void CreateInst(string prefabPath = "") | |
{ | |
if (null != _inst) | |
{ | |
return; | |
} | |
if (string.IsNullOrEmpty(prefabPath)) | |
{ | |
var obj = new GameObject($"Singleton_{typeof(T).FullName}"); | |
DontDestroyOnLoad(obj); | |
_inst = obj.AddComponent<T>(); | |
} | |
else | |
{ | |
var obj = Instantiate(Resources.Load<GameObject>(prefabPath)); | |
obj.name = $"Singleton_{typeof(T).FullName}"; | |
DontDestroyOnLoad(obj); | |
_inst = obj.GetComponent<T>(); | |
} | |
} | |
public static void DestroyInst() | |
{ | |
Destroy(_inst.gameObject); | |
} | |
private static T _inst; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment