SingletonBehavior – Auto gameobject management
Posted by SteamPunkProgrammerJul 31
Through all my development in unity, having a Monobehavior be a singleton has been very useful in a lot of cases. Making a gameObject a singleton isn’t very difficult but it can be a little annoying to do over and over again, so I’ve made a child class for MonoBehavior.
Here is the class itself
using System.Collections;
public class SingletonBehaviour
{
static T instance;
static public T Instance
{
get
{
if (instance == null)
{
instance = MonoBehaviour.FindObjectOfType(typeof(T)) as T;
if (instance == null)
{
GameObject go = new GameObject(typeof(T).ToString());
instance = go.AddComponent
}
}
return instance;
}
}
protected virtual void Start()
{
if (instance != null && instance != this)
{
Destroy(gameObject);
return;
}
DontDestroyOnLoad(gameObject);
}
}
implementing it in a class is super easy.
{
}
No comments