Created
February 23, 2022 20:18
-
-
Save redheadgektor/0cd72ff9dcd8f4b8243a24bd2435d0e1 to your computer and use it in GitHub Desktop.
A simple class that implements a static MonoBehaviour
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; | |
/* | |
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