Last active
July 27, 2024 18:10
-
-
Save 123tris/468cd76aed50610d62379272a2d9596d to your computer and use it in GitHub Desktop.
A way to retrieve and cache singleton/manage type monobehaviours
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 static class CachedReference<T> where T : MonoBehaviour | |
{ | |
private static T cachedReference; | |
/// <summary> Returns null when it cannot find the type </summary> | |
public static T FindCachedObject(bool includeInactive = true) | |
{ | |
if (cachedReference == null) | |
{ | |
cachedReference = Object.FindObjectOfType<T>(includeInactive); | |
} | |
Assert.IsTrue(cachedReference != null, $"Couldn't find an instance of type {typeof(T).Name} in the currently loaded scenes. Make sure you have attached {typeof(T).Name} in the scene somewhere"); | |
return cachedReference; | |
} | |
public static bool ReferenceExists() => cachedReference != null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment