Forked from vasyaPP/gist:6d88aee67ae6361c0a47e469894528c8
Last active
January 14, 2021 21:20
-
-
Save stakira/a3506e69708f2ee21eeda8a85c61f3fe to your computer and use it in GitHub Desktop.
Unity MonoBehaviour Singleton
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
using System; | |
using UnityEngine; | |
namespace FarFarEast | |
{ | |
/// <summary> | |
/// Inherit from this base class to create a singleton. | |
/// e.g. public class MyClassName : Singleton<MyClassName> {} | |
/// </summary> | |
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour | |
{ | |
// Check to see if we're about to be destroyed. | |
private static bool m_ShuttingDown = false; | |
private static Lazy<T> m_Instance = new Lazy<T>(Factory); | |
private static T Factory() | |
{ | |
// Search for existing instance. | |
T instance = (T)FindObjectOfType(typeof(T)); | |
// Create new instance if one doesn't already exist. | |
if (instance == null) | |
{ | |
// Need to create a new GameObject to attach the singleton to. | |
var singletonObject = new GameObject(); | |
instance = singletonObject.AddComponent<T>(); | |
singletonObject.name = typeof(T).ToString() + " (Singleton)"; | |
// Make instance persistent. | |
DontDestroyOnLoad(singletonObject); | |
} | |
return instance; | |
} | |
/// <summary> | |
/// Access singleton instance through this propriety. | |
/// </summary> | |
public static T Instance | |
{ | |
get | |
{ | |
if (m_ShuttingDown) | |
{ | |
Debug.LogWarning("[Singleton] Instance '" + typeof(T) + "' already destroyed. Returning null."); | |
return null; | |
} | |
return m_Instance.Value; | |
} | |
} | |
private void OnApplicationQuit() | |
{ | |
m_ShuttingDown = true; | |
} | |
private void OnDestroy() | |
{ | |
m_ShuttingDown = true; | |
} | |
} | |
} |
Why do you use a lock statement? Because multithreading is not supported here 🤔
You are right. The lock is most likely necessary, or can be done better. I forked this file without change a while back. Let me give it a shot.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Why do you use a lock statement? Because multithreading is not supported here 🤔