Last active
March 14, 2022 06:06
-
-
Save tsubaki/481a0460698bf03fd259 to your computer and use it in GitHub Desktop.
少しだけ高速なシングルトン。初回検索を特定のタグから行う事で少しだけ高速化(倍〜3倍)。awakeフェイズ以降に呼び出す場合は以前と余り変わらず。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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