Game Development Reference
In-Depth Information
Understanding singleton objects
and statics
Some classes are fundamentally different from others in the way they should
be instantiated. Most classes define a template for a collection of properties and
behaviors that might be instantiated many times in a scene as GameObjects . An
enemy class can be used to instantiate many enemy objects, a power-up class for
many power-up objects, and so on. However, some classes such as GameManager ,
HighScoreManager , AudioManager , or SaveGameManager are intended to exist
as a lone entity, one that consolidates a unified set of behaviors. In short, there
should only ever be one instance of the class at any one time and never more than
one. To have more than one instance would either be nonsensical or damage the
object's authority and usefulness in some way. These kinds of objects are known as
singletons. Singletons are often persistent objects that survive across scenes, though
they need not be. The only essential ingredient in a singleton (which makes it what
it is) is that there cannot be more than one instance of the class in memory at any
one time. Let's now create a singleton object in the context of making a sample
GameManager class.
Practically, every game has a GameManager or GameController class; and these
are almost always singleton objects that persist. The GameManager is essentially
responsible for all high-level functionality in a game. It must determine whether a
game is paused, whether the win condition has been satisfied, and have a reliable
way of knowing what's happening in the game at any one time, among others.
Consider the sample beginnings of a GameManager in the following code sample 3-13:
using UnityEngine;
using System.Collections;
//-----------------------------------------
//Sample Game Manager class
public class GameManager : MonoBehaviour
{
//-----------------------------------------
//High score
public int HighScore = 0;
//Is game paused
public bool IsPaused = false;
//Is player input allowed
public bool InputAllowed = true;
//-----------------------------------------
// Use this for initialization
 
Search WWH ::




Custom Search