Skip to content

Instantly share code, notes, and snippets.

@redheadgektor
Created February 23, 2022 20:18
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 redheadgektor/0cd72ff9dcd8f4b8243a24bd2435d0e1 to your computer and use it in GitHub Desktop.
Save redheadgektor/0cd72ff9dcd8f4b8243a24bd2435d0e1 to your computer and use it in GitHub Desktop.
A simple class that implements a static MonoBehaviour
using UnityEngine;
/*
Creating new class
public class MyClass : StaticMonoBehaviour<MyClass>
{
public void MyMethod(){}
}
Usage
MyClass.Get().MyMethod();
When you call Get(), a new game object is created, a component of your class is added, and a static reference to it is specified.
When the Get() method is called again, only the reference will be returned!
*/
public abstract class StaticMonoBehaviour<T> : MonoBehaviour where T : MonoBehaviour
{
private static T Instance;
public static T Get(bool DontDestroy = true)
{
if(Instance == null)
{
GameObject go = new GameObject(typeof(T).Name+"_Static");
if (DontDestroy)
{
DontDestroyOnLoad(go);
}
Instance = go.AddComponent<T>();
}
return Instance;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment