Skip to content

Instantly share code, notes, and snippets.

@saitocastel1900
Created October 24, 2022 10:48
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 saitocastel1900/0b90e5ea9153964a90d42af1c4c88f96 to your computer and use it in GitHub Desktop.
Save saitocastel1900/0b90e5ea9153964a90d42af1c4c88f96 to your computer and use it in GitHub Desktop.
public class SingletonMonoBehaviour<T> : MonoBehaviour where T : MonoBehaviour
{
/// <summary>
/// インスタンス
/// </summary>
private static T _instance;
/// <summary>
/// インスタンスのゲッター
/// </summary>
public static T Instance
{
get
{
//インスタンスのnullチェック(初回起動時)
if (_instance == null)
{
T[] instances = null;
instances = FindObjectsOfType<T>();
//FindObjectOfType(typeof(T)) as T;  こちらで大丈夫です
//インスタンスが存在なし
if (instances.Length == 0)
{
Debug.LogError(typeof(T) + "インスタンスはありません。アタッチし忘れていませんか?");
return null;
}
//インスタンスが複数個存在している...
else if (instances.Length >= 2)
{
Debug.LogError(typeof(T) + "インスタンスが複数個生成されています。");
return null;
}
//インスタンスが1個存在している(平常)
else
{
_instance = instances[0];
Debug.Log(typeof(T) + "インスタンスが1個生成されています。正常です。");
}
}
return _instance;
}
}
}
public class Singleton2:SingletonMonoBehaviour<Singleton2>
{
private void Awake()
{
#region Singleton
if (this != Instance)
{
Debug.LogError("インスタンスが既に存在しています。インスタンスを一つにするためこのインスタンスを破棄します");
//Destroy(this.gameObject);
return;
}
#endregion
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment