Singleton

From Unify Community Wiki
Revision as of 10:23, 21 January 2009 by AngryAnt (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

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>

Personal tools
Namespaces

Variants
Actions
Navigation
Extras
Toolbox