Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
少しだけ高速なシングルトン。初回検索を特定のタグから行う事で少しだけ高速化(倍〜3倍)。awakeフェイズ以降に呼び出す場合は以前と余り変わらず。
using UnityEngine;
using System;
using System.Collections;
public abstract class SingletonMonoBehaviourFast<T> : MonoBehaviour where T : SingletonMonoBehaviourFast<T>
{
protected static readonly string[] findTags =
{
"GameController",
};
protected static T instance;
public static T Instance {
get {
if (instance == null) {
Type type = typeof(T);
foreach( var tag in findTags )
{
GameObject[] objs = GameObject.FindGameObjectsWithTag(tag);
for(int j=0; j<objs.Length; j++)
{
instance = (T)objs[j].GetComponent(type);
if( instance != null)
return instance;
}
}
Debug.LogWarning( string.Format("{0} is not found", type.Name) );
}
return instance;
}
}
virtual 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
You can’t perform that action at this time.