Skip to content

Instantly share code, notes, and snippets.

@taross-f
Forked from tsubaki/SingletonMonoBehaviour.cs
Last active October 8, 2015 01:43
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 taross-f/5e9eca63642d4bc2b7c7 to your computer and use it in GitHub Desktop.
Save taross-f/5e9eca63642d4bc2b7c7 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