Skip to content

Instantly share code, notes, and snippets.

@mitu217
Created June 25, 2015 16:38
Show Gist options
  • Save mitu217/00552a5ee7c84f4d5390 to your computer and use it in GitHub Desktop.
Save mitu217/00552a5ee7c84f4d5390 to your computer and use it in GitHub Desktop.
SingletonClass for Unity
using UnityEngine;
public class SingletonMonoBehaviour<T> : MonoBehaviour where T : SingletonMonoBehaviour<T>
{
protected static T instance;
/// <summary>
/// インスタンスの取得
/// </summary>
public static T Instance {
get {
if (instance == null) {
instance = (T)FindObjectOfType (typeof(T));
if (instance == null) {
Debug.LogWarning (typeof(T) + "is nothing");
}
}
return instance;
}
}
/// <summary>
/// シーン開始時にインスタンスの生成をおこなう
/// </summary>
protected void Awake() {
CheckInstance();
}
/// <summary>
/// インスタンスが存在するかのチェック
/// </summary>
/// <value> なければ新たに生成 </value>
protected bool CheckInstance() {
if( instance == null) {
instance = (T)this;
return true;
} else if( Instance == this ) {
/// シーンを通して存在できるように
DontDestroyOnLoad (this.gameObject);
return true;
}
Destroy(this);
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment