Created
June 25, 2015 16:38
-
-
Save mitu217/00552a5ee7c84f4d5390 to your computer and use it in GitHub Desktop.
SingletonClass for Unity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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