使用:直接类继承
例 ItemData :MonoSingleton<ItemData>
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 单例模板类
/// </summary>
//Where T: 类 指的是约束T只能是该类类型或者该类的派生类
public class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
{
//public static T Instance { get; private set; }
//private void Awake()
//{
// Instance = this as T;
//}
//按需加载
private static T instance;
public static T Instance
{
get
{
//为instance赋值
//instance = this;
if (instance == null)
{
//在场景中查找T类型引用
instance = FindObjectOfType<T> ();
if (instance == null)
{
//立即执行Awake
new GameObject ("Singleton of " + typeof (T).Name).AddComponent<T> ();
} else
{
//通知子类进行初始化
instance.Init ();
}
}
return instance;
}
}
protected virtual void Init () { }
protected void Awake ()
{
if (instance == null)
{
instance = this as T;
Init ();
}
}
}