【常用】单例
using UnityEngine;
using System.Collections;/// <summary>
/// 腳本的單例類
/// </summary>
public class MonoSingleton<T> : MonoBehaviour where T:MonoSingleton<T>
{//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<T>();}//子類可能需要在此執行一段代碼……instance.Init();}return instance;}}//餓漢private void Awake(){//當場景切換時 不銷毀當前游戲對象//DontDestroyOnLoad(gameObject);//Instance = this as T;}protected virtual void Init() { }
}
?
總結
- 上一篇: 【常用】截取相机图片截图功能
- 下一篇: 【常用】查找子物体