Skip to content

Instantly share code, notes, and snippets.

@sunny352
Last active October 6, 2019 07:36
Show Gist options
  • Save sunny352/3e168d85d070829b45f1caedf389a67d to your computer and use it in GitHub Desktop.
Save sunny352/3e168d85d070829b45f1caedf389a67d to your computer and use it in GitHub Desktop.
Unity中的单例模板
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