using UnityEngine;
using System.Collections;///
/// 脚本的单例类
///
public class MonoSingleton : MonoBehaviour where T:MonoSingleton
{//public static T Instance { get; private set; }private static T instance;public static T Instance{//懒汉//按需分配,如果在Awake方法中需要调用,就在Awake方法中创建get{if (instance == null){//在场景中查找已经存在的对象引用instance = FindObjectOfType(typeof(T)) as T;if (instance == null){ //创建脚本对象string goName = "Singleton of "+typeof(T);instance = new GameObject(goName).AddComponent();}//子类可能需要在此执行一段代码……instance.Init();}return instance;}}//饿汉private void Awake(){//当场景切换时 不销毁当前游戏对象//DontDestroyOnLoad(gameObject);//Instance = this as T;}protected virtual void Init() { }
}