Unity – Singleton GameComponent

      Comments Off on Unity – Singleton GameComponent

Sometimes you have components that will only be in the scene once that you need access to from several of your other components. In these situations you can have your components all have a public reference to those other components and wire them all up in the editor, but if you’re guaranteed to have 1 instance in the scene and it’s a commonly used item, and Singleton pattern would be a better way to go. The singleton design pattern restricts instantiation of a type to one instance and provides a static accessor to allow calls from a variety of sources without an instance reference.

http://en.wikipedia.org/wiki/Singleton_pattern

SingletonImage1

I use Awake to assign the instance because it occurs before all Start calls and is where unity recommends doing any logic that would normal be done in the constructor.

Consuming code that accesses the component:

SingletonImage2

http://docs.unity3d.com/ScriptReference/MonoBehaviour.Awake.html

This can be helpful when accessing classes that hold level information, audio and FX management, game settings, and many more things that need to be globally accessible and only exists once in your scene.

If you’re a Visual Studio user, here’s a code snippet you can use. keyword: usingleton

Snippet Download