Skip to content

Instantly share code, notes, and snippets.

@tsubaki
Created July 25, 2013 02:37
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 tsubaki/6076474 to your computer and use it in GitHub Desktop.
Save tsubaki/6076474 to your computer and use it in GitHub Desktop.
Unity用シングルトン
using UnityEngine;
public class SampleInstance : SingletonMonoBehaviour<SampleInstance>
{
}
public class SingletonMonoBehaviour<T> : MonoBehaviour where T : MonoBehaviour
{
private static T instance;
public static T Instance {
get {
if (instance == null) {
instance = (T)FindObjectOfType (typeof(T));
if (instance == null) {
Debug.LogError (typeof(T) + "is nothing");
}
}
return instance;
}
}
protected void Awake()
{
CheckInstance();
}
protected bool CheckInstance()
{
if( this == Instance){ return true;}
Destroy(this);
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment