Skip to content

Instantly share code, notes, and snippets.

@tsubaki
Last active March 14, 2022 06:06
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tsubaki/481a0460698bf03fd259 to your computer and use it in GitHub Desktop.
Save tsubaki/481a0460698bf03fd259 to your computer and use it in GitHub Desktop.
少しだけ高速なシングルトン。初回検索を特定のタグから行う事で少しだけ高速化(倍〜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