Created
July 26, 2017 03:05
-
-
Save mao-test-h/4f5205bc22cdadaa1f01d9b286c48a56 to your computer and use it in GitHub Desktop.
Unity向け シングルトン基底クラス(MonoBehaviour継承)
This file contains hidden or 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; | |
namespace Singleton | |
{ | |
/// <summary> | |
/// シングルトン基底クラス(MonoBehaviour継承) | |
/// </summary> | |
public abstract class SingletonMonoBehaviour<T> : MonoBehaviour where T : SingletonMonoBehaviour<T> | |
{ | |
static T instance; | |
public static T Instance | |
{ | |
get | |
{ | |
if (instance == null) | |
{ | |
instance = (T)FindObjectOfType(typeof(T)); | |
if ((instance == null)) | |
{ | |
Debug.LogWarning(typeof(T) + "is nothing"); | |
} | |
} | |
return instance; | |
} | |
} | |
protected virtual void Awake() | |
{ | |
if (this.CheckInstance()) | |
{ | |
DontDestroyOnLoad(this.gameObject); | |
} | |
} | |
bool CheckInstance() | |
{ | |
if (instance == null) | |
{ | |
instance = (T)this; | |
return true; | |
} | |
else if (Instance == this) | |
{ | |
return true; | |
} | |
Destroy(this.gameObject); | |
return false; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment