Singleton
By AngryAnt.
Description
People have recently asked about singleton creation quite often in the IRC channel so rather than retyping a basic implementation each time, I'll have this to link to. Yay! :)
Curious, but not quite sure what a singleton is? Ask a friend: [1]
Singletons are generally handy for providing easy access to game state and control code. I've provided example implementation for a basic class type which needn't be attached to a game object in order to function and after this an implementation which works as any other component.
Members of both singleton types are accessed the same way:
<csharp>MySingleton.Instance.MySingletonMember;</csharp>
Note, however that for the component-based singleton (the second implementation), you shouldn't attempt to access the instance earlier than in Start of the calling component.
The non-component example
<csharp>public class MySingleton { private static MySingleton instance;
public MySingleton() { if( instance != null ) { Debug.LogError( "Cannot have two instances of singleton. Self destruction in 3..." ); return; }
instance = this; }
public static MySingleton Instance { get { if( instance == null ) { new MySingleton(); }
return instance; } } }</csharp>
Component-based example
<csharp>using UnityEngine;
public class MySingleton : MonoBehaviour { private static MySingleton instance;
public void Awake() { if( instance != null ) { Debug.LogError( "Cannot have two instances of singleton. Self destruction in 3..." ); Destroy( this ); return; }
instance = this; }
public static MySingleton Instance { get { return instance; } }
public void OnApplicationQuit() { instance = null; } }</csharp>