Skip to content

Instantly share code, notes, and snippets.

@123tris
Last active June 25, 2024 12:48
Show Gist options
  • Save 123tris/468cd76aed50610d62379272a2d9596d to your computer and use it in GitHub Desktop.
Save 123tris/468cd76aed50610d62379272a2d9596d to your computer and use it in GitHub Desktop.
A way to retrieve and cache singleton/manage type monobehaviours
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