Created
May 19, 2023 18:01
-
-
Save iwaken71/f29a6e6d82aef30b5bbedc092165c403 to your computer and use it in GitHub Desktop.
This file contains 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
/// <summary> | |
/// シングルトンパターン(MonoBehaviour) | |
/// </summary> | |
/// <typeparam name="T"></typeparam> | |
public abstract class SingletonMonoBehaviour<T> : MonoBehaviour where T : MonoBehaviour | |
{ | |
private static T _instance; | |
private static object _lock = new object(); | |
// アプリが終了しているかどうかのフラグ | |
private static bool applicationIsQuitting = false; | |
/// <summary> | |
/// シングルトンインスタンス | |
/// </summary> | |
public static T Instance | |
{ | |
get | |
{ | |
if (applicationIsQuitting) | |
{ | |
Debug.LogWarning("[Singleton] Instance '" + typeof(T) + | |
"' already destroyed on application quit." + | |
" Won't create again - returning null."); | |
return null; | |
} | |
lock (_lock) | |
{ | |
if (_instance == null) | |
{ | |
_instance = (T) FindObjectOfType(typeof(T)); | |
if (FindObjectsOfType(typeof(T)).Length > 1) | |
{ | |
Debug.LogError("[Singleton] Something went really wrong " + | |
" -there should never be more than 1 singleton!" + | |
" Reopening the scene may fix it."); | |
return _instance; | |
} | |
if (_instance == null) | |
{ | |
GameObject singleton = new GameObject(); | |
_instance = singleton.AddComponent<T> (); | |
singleton.name = "(singleton)" + typeof(T).ToString(); | |
DontDestroyOnLoad(singleton); | |
Debug.Log("[Singleton] An instance of " + typeof(T) + | |
" is needed in the scene, so '" + singleton + | |
"' was created with DontDestroyOnLoad."); | |
} | |
else | |
{ | |
Debug.Log("[Singleton] Using instance already created: " + | |
_instance.gameObject.name); | |
} | |
} | |
return _instance; | |
} | |
} | |
} | |
public virtual void OnDestroy() | |
{ | |
applicationIsQuitting = true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment