Viewing entries tagged
singleton

Generic Singleton MonoBehavior Part 2:  Singleton Self-Loading Prefab

Generic Singleton MonoBehavior Part 2: Singleton Self-Loading Prefab

I had a previous post about singletons in Unity3D and have since added a useful functionality to that class.  One of the useful features of a singleton is that it is self instantiating.  But what if you want to use the Unity editor to expose some public variables and have some other assets hooked into your singleton?  So since you are probably using prefabs to manage game components in your scenes anyway, seems like it might be useful to have a self-loading prefab for components such as the player or a gui controller. 

Generic Singleton MonoBehavior Class

Generic Singleton MonoBehavior Class

In Unity3D having a singleton class is very useful, whether for "global" state or simply for the convenience of having a static accessor so you don't have to have lots of: <code>FindObjectOfType(typeof(Builder)) as Builder;</code>

So you code up a C# singleton and then realize that you actually need it to be a MonoBehavior, not just a ScriptableObject -- say you want the singleton to run coroutines, or have a transform, or any other MonoBehavior feature.  But monobehaviors can't be initialized with a constructor. So what you want is a monobehavior pseudo singleton pattern.