Skip to content

Instantly share code, notes, and snippets.

@stakira
Forked from vasyaPP/gist:6d88aee67ae6361c0a47e469894528c8
Last active January 14, 2021 21:20
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 stakira/a3506e69708f2ee21eeda8a85c61f3fe to your computer and use it in GitHub Desktop.
Save stakira/a3506e69708f2ee21eeda8a85c61f3fe to your computer and use it in GitHub Desktop.
Unity MonoBehaviour Singleton
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;
}
}
}
@listopad
Copy link

Why do you use a lock statement? Because multithreading is not supported here 🤔

@stakira
Copy link
Author

stakira commented Jan 14, 2021

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