Skip to content

Instantly share code, notes, and snippets.

@tsubaki
Last active August 13, 2021 12:45
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save tsubaki/e0406377a1b014754894 to your computer and use it in GitHub Desktop.
Save tsubaki/e0406377a1b014754894 to your computer and use it in GitHub Desktop.
旧シングルトンの改良版。初回起動時にインスタンスが登録されていなければ自身を登録する
using UnityEngine;
using System.Collections;
public class SingletonMonoBehaviour<T> : MonoBehaviour where T : SingletonMonoBehaviour<T>
{
protected 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 void Awake()
{
CheckInstance();
}
protected bool CheckInstance()
{
if( instance == null)
{
instance = (T)this;
return true;
}else if( Instance == this )
{
return true;
}
Destroy(this);
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment