继承Monobehaviour的单例
/***********************
* Title: 单例
* FileName: SingletonMono
* Date: 2020-07-16 16:58:59
* Author: 一禅
* Version: 1.0
* UnityVersion: 2019.2.4f1
* Description: 继承Monobehaviour的单例
* Func:
* -
***********************/
using UnityEngine;
using System.Collections;
//继承MonoBehaviour 的单例模版,别的脚本可以直接用,省去七行代码
public abstract class SingletonMono<T> : MonoBehaviour where T : SingletonMono<T>
{
#region 单例
private static T instance;
public static T Instance
{
get
{
if (instance == null)
{
GameObject obj = new GameObject(typeof(T).Name);
instance = obj.AddComponent<T>();
}
return instance;
}
}
#endregion
//可重写的Awake虚方法,用于实例化对象
protected virtual void Awake()
{
instance = this as T;
}
}
不继承Monobehaviour的单例
public abstract class Singleton<T> : System.IDisposable where T : new()
{
private static T instance;
public static T Instance
{
get
{
if (instance == null)
{
instance = new T();
}
return instance;
}
}
public virtual void Dispose()
{
}
}
网友评论