MonoSingleton

From Headbone Creative
Revision as of 18:30, 20 April 2013 by Tyson Joehler (Talk | contribs)

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

This class implements a way create a Singleton object that derives from MonoBehaviour.

A Singleton is a kind of object that is globally accessible. There is only one instance of this object allowed to exist at any given time; however if you attach a script that derives from this to a GameObject that is in your scene and re-load the scene, you will end up with multiple copies of the singleton GameObject in the scene. For this reason, it is recommended that you use a ResourceSingleton if you wish to configure the public variables of deriving sub-classes that use this script.

This is based upon work from the Unify Community wiki: Generic Based Singleton for MonoBehaviours

Contents

Usage

To use this class, make a new class that derives from it, like this:

  public class ScoreKeeper : MonoSingleton<ScoreKeeper> {
     int currentScore = 0;
  };

To access this class from other scripts, use the public static instance member as follows:

  ScoreKeeper.instance.currentScore += 1;

Public Variables

instance : T

This will return the only instance of this class allowed to exist. If there is no GameObject containing this object in the scene, a new one is created. This is a static, read-only variable, and is the only way this deriving sub-classes should be accessed.

Virtual Functions

void Init ()

This is where deriving sub-classes can initialize their data. It should be used instead of Start ().

void OnAppQuit ()

This function is what deriving sub-classes should use to do things when the application closes.

Personal tools
Namespaces

Variants
Actions
Navigation
Toolbox