本文提供一个方便简单的单例类,有需要的地方继承就可以实现单例了,当前此处是没有继承MonoBehaviour的,废话不多说,上代码:
using UnityEngine;
using System;
using System.Collections.Generic;
// using System.Text;
using System.Reflection;
public class Singleton<T> where T : class
{
private static object ms_SyncRoot = new object();
private static T ms_Instance;
public static readonly Type[] ms_EmptyTypes = new Type[0];
public static T Instance
{
get
{
if (ms_Instance == null)
{
lock (ms_SyncRoot)
{
if (ms_Instance == null)
{
ConstructorInfo ci = typeof(T).GetConstructor(
BindingFlags.NonPublic | BindingFlags.Instance, null, ms_EmptyTypes, null);
if (ci == null)
{
throw new InvalidOperationException("class must contain a private constructor");
}
ms_Instance = (T)ci.Invoke(null);
//instance = Activator.CreateInstance(typeof(T)) as T;
}
}
}
return ms_Instance;
}
}
}
所以咋使用?举个例子:
public class XXX : Singleton<XXX>
{
/// <summary>
/// 空构造函数
/// </summary>
private XXX()
{
}
}