Skip to content

Instantly share code, notes, and snippets.

@mao-test-h
Created July 26, 2017 03:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mao-test-h/4f5205bc22cdadaa1f01d9b286c48a56 to your computer and use it in GitHub Desktop.
Save mao-test-h/4f5205bc22cdadaa1f01d9b286c48a56 to your computer and use it in GitHub Desktop.
Unity向け シングルトン基底クラス(MonoBehaviour継承)
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