普通类单例几种制作方式如下:
/*
* Author:W
* 单例模式
* 【注意】会随着场景的切换而销毁
*/
public class Singleton_Common
{
/// <summary>
/// 普通的单例模式
/// </summary>
private static Singleton_Common _instance;
public static Singleton_Common Instance
{
get
{
if (_instance == null)
{
_instance = new Singleton_Common();
}
return _instance;
}
}
/// <summary>
/// 构造方法私有化
/// </summary>
private Singleton_Common() { }
}
/// <summary>
/// 普通单例的基类即接口
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract class Single_Template<T> where T: class, new()
{
protected static T _instance;
public static T Instance
{
get
{
if (_instance == null)
{
_instance = new T();
}
return _instance;
}
}
protected Single_Template()
{
if (_instance != null)
{
Debug.LogError("This "+(typeof(T)).ToString()+" Singleton Instance is not null");
}
Init();
}
public virtual void Init()
{
}
}
/// <summary>
/// 在多线程中使用中保证一个单例不会被多次new的情况
/// </summary>
public class Singleton_MultiThread
{
private static volatile Singleton_MultiThread _instance;
private static object locker = new object();
public static Singleton_MultiThread Instance
{
get
{
if (_instance == null)
{
lock (locker)
{
if (_instance == null)
{
_instance = new Singleton_MultiThread();
}
}
}
return _instance;
}
}
}
继承于MonoBehaviour类的单例几种制作方式如下:
/// <summary>
/// 继承于MonoBehaviour,最简单单例
/// 【注意】:会随着场景的切换而销毁
/// </summary>
public class Singleton_Mono_Simple : MonoBehaviour
{
public static Singleton_Mono_Simple Instance;
void Awake()
{
Instance = this;
}
}
/// <summary>
/// 继承于MonoBehaviour,单例的规范写法
/// 【注意】:会随着场景的切换而销毁
/// </summary>
public class Singleton_Mono_Common : MonoBehaviour
{
private static Singleton_Mono_Common _instance;
public static Singleton_Mono_Common Instance
{
get
{
if (_instance == null)
_instance = FindObjectOfType(typeof(Singleton_Mono_Common)) as Singleton_Mono_Common;
return _instance;
}
}
void Awake()
{
_instance = this;
}
}
/// <summary>
/// 继承于MonoBehaviour,单例模式的基类即接口
/// 【注意】不会随着场景的切换而销毁
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract class Singleton_Mono_template<T> : MonoBehaviour where T:Singleton_Mono_template<T>
{
protected static T _instance = null;
public static T Instance
{
get
{
if (_instance == null)
{
string name = typeof(T).Name;
GameObject singleObj = GameObject.Find(name);
if (singleObj == null)
{
singleObj = new GameObject(name);
DontDestroyOnLoad(singleObj);
}
_instance = singleObj.GetComponent<T>();
if (_instance == null)
_instance = singleObj.AddComponent<T>();
}
return _instance;
}
}
}