单例日常使用模板

单例

单例是日常使用中不可避免的工具类,基本大多项目都需要使用到。本文写一个直接拿来使用的单例就可以。

使用方法

在这里插入图片描述

技术细节

代码细节

using UnityEngine;


	public class Singleton<T> : MonoBehaviour where T : Singleton<T> {
		private static T instance;

		public static T Instance {
			get {
				return instance;
			}
		}

		public static bool IsInitialized {
			get {
				return instance != null;
			}
		}

		protected virtual void Awake () {
			if (instance != null) {
				Debug.LogErrorFormat ("Trying to instantiate a second instance of singleton class {0}", GetType ().Name);
			} else {
				instance = (T)this;
			}
		}

		protected virtual void OnDestroy () {
			if (instance == this) {
				instance = null;
			}
		}
	}


小结

若需要其他功能可自行扩展。