Last active
October 22, 2024 02:00
-
-
Save 123tris/f0964841c92a66412a9399c81c86731b to your computer and use it in GitHub Desktop.
Singleton for Unity. Could possibly be improved on.
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 UnityEngine; | |
using UnityEngine.Assertions; | |
public class Singleton<T> : BaseBehaviour where T : MonoBehaviour | |
{ | |
public static T Instance => GetInstance(); | |
/// <summary>GetInstance gets called by the getter Instance, however GetInstance can be used to get extra control such as turning off exceptions and allowing null or generate the instance when it can't be found </summary> | |
public static T GetInstance(bool throwException = true, bool generateInstance = false) | |
{ | |
if (instance == null) | |
{ | |
T[] foundInstances = FindObjectsOfType<T>(true); | |
if (foundInstances.Length == 0) | |
{ | |
if (generateInstance) | |
{ | |
GameObject gameObject = new GameObject($"{typeof(T).Name} Manager"); | |
instance = gameObject.AddComponent<T>(); | |
} | |
} | |
else | |
{ | |
if (foundInstances.Length > 1) | |
Debug.LogError($"You have multiple instances of a Singleton of type {typeof(T).Name}"); | |
instance = foundInstances[0]; | |
} | |
if (throwException) | |
Assert.IsTrue(instance, $"The component {typeof(T).FullName}, could not be found in the scene"); | |
} | |
return instance; | |
} | |
private static T instance; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment