Difference between revisions of "MonoSingleton"

From Headbone Creative
Jump to: navigation, search
(Initial page, includes API information and categories)
 
(Added link to unify community wiki)
Line 2: Line 2:
  
 
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.  
 
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: [http://wiki.unity3d.com/index.php?title=Singleton#Generic_Based_Singleton_for_MonoBehaviours Generic Based Singleton for MonoBehaviours]
  
 
== Usage ==
 
== Usage ==

Revision as of 18:29, 20 April 2013

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;
  };

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