Singleton<T>
using System;
using System.Reflection;
namespace LJFramework
{
public abstract class Singleton<T> where T : Singleton<T>
{
private static T mInstance;
public static T Instance
{
get
{
if (mInstance == null)
{
var ctors = typeof(T).GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic);
var ctor = Array.Find(ctors, c => c.GetParameters().Length == 0);
if (ctor == null)
{
throw new Exception("Non-public ctor() not found!");
}
mInstance = ctor.Invoke(null) as T;
}
return mInstance;
}
}
protected Singleton()
{
}
}
}
SingletonExample
using UnityEngine;
namespace LJFramework
{
public class SingletonExample : Singleton<SingletonExample>
{
private SingletonExample()
{
Debug.Log("singtleton example ctor");
}
#if UNITY_EDITOR
[UnityEditor.MenuItem("LJFramework/Examples/5.SingletonExample", false, 5)]
static void MenuClicked()
{
var initInstance = SingletonExample.Instance;
initInstance = SingletonExample.Instance;
}
#endif
}
}
MonoSingleton<T>:MonoBehaviour
using UnityEngine;
namespace LJFramework
{
public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
{
protected static T mInstance = null;
public static T Instance
{
get
{
if (mInstance == null)
{
mInstance = FindObjectOfType<T>();
if (FindObjectsOfType<T>().Length > 1)
{
Debug.LogWarning("More than 1");
return mInstance;
}
if (mInstance == null)
{
var instanceName = typeof(T).Name;
Debug.LogFormat("Instance Name: {0}", instanceName);
var instanceObj = GameObject.Find(instanceName);
if (!instanceObj)
instanceObj = new GameObject(instanceName);
mInstance = instanceObj.AddComponent<T>();
DontDestroyOnLoad(instanceObj); //保证实例例不不会被释放
Debug.LogFormat("Add New Singleton {0} in Game!",
instanceName);
}
else
{
Debug.LogFormat("Already exist: {0}", mInstance.name);
}
}
return mInstance;
}
}
protected virtual void OnDestroy()
{
mInstance = null;
}
}
}
MonoSingletonExample
using UnityEngine;
namespace LJFramework
{
public class MonoSingletonExample : MonoSingleton<MonoSingletonExample>
{
#if UNITY_EDITOR
[UnityEditor.MenuItem("LJFramework/Examples/6.MonoSingletonExample",
false, 6)]
private static void MenuClicked()
{
UnityEditor.EditorApplication.isPlaying = true;
}
#endif
[RuntimeInitializeOnLoadMethod]
private static void Example()
{
var initInstance = MonoSingletonExample.Instance;
initInstance = MonoSingletonExample.Instance;
}
}
}