【Unity】シングルトン

何度も掘り返される、シーン上に一つしかないスクリプト。

使用する際はSingletonMonoBehaviour<自身のクラス名>を継承して使用。

コピペの場合は”using BlueBreath;”

using UnityEngine;
using System;

namespace BlueBreath
{
	public abstract class SingletonMonoBehaviour<T> : MonoBehaviour where T : MonoBehaviour{
		private static T instance;
		public static T Instance
		{
			get{
				if (instance == null) {
					Type t = typeof(T);
					instance = (T)FindObjectOfType (t);
					if (instance == null) {
						Debug.LogError (t + "is Not Found");
					}
				}
				return instance;
			}
		}

		virtual protected void Awake(){
			CheckInstance();
		}
		protected bool CheckInstance(){
			if (instance == null) {
				instance = this as T;
				return true;
			} else if (Instance == this) {
				return true;
			}
			Destroy (this);
			return false;
		}
	}
}
スポンサーリンク

参考

Singleton: Unify Community Wiki

タイトルとURLをコピーしました