Game Development Reference
In-Depth Information
09 public static GameManager Instance
10 {
11 get
12 {
13 if (instance == null) instance = new GameObject ("GameManager").
AddComponent<GameManager>(); //create game manager object if required
14 return instance;
15 }
16 }
17
18 //--------------------------------------------------------------
19 //Internal reference to single active instance of object - for singleton behaviour
20 private static GameManager instance = null;
21 }
Here we add a public and static C# property, called Instance . The name is not essential, but its
purpose is to return a reference to the active GameManager instance. If there is no currently active
instance at the time of the call, then one is created and a reference to that instance is returned. As
we'll see, most other classes in our game will use this property to retrieve a reference to the active
GameManager instance whenever they need to access and invoke functions on the Game Manager.
Now consider Listing 4-15.
Listing 4-15. Completing the Singleton Class
01 //--------------------------------------------------------------
02 using UnityEngine;
03 using System.Collections;
04 //--------------------------------------------------------------
05 public class GameManager : MonoBehaviour
06 {
07 //--------------------------------------------------------------
08 //C# property to retrieve currently active instance of object, if any
09 public static GameManager Instance
10 {
11 get
12 {
13 if (instance == null) instance = new GameObject ("GameManager").
AddComponent<GameManager>(); //create game manager object if required
14 return instance;
15 }
16 }
17
18 //--------------------------------------------------------------
19 //Internal reference to single active instance of object - for singleton behaviour
20 private static GameManager instance = null;
21
22 //--------------------------------------------------------------
23 // Called before Start on object creation
24 void Awake ()
25 {
26 //Check if there is an existing instance of this object
27 if((instance) && (instance.GetInstanceID() != GetInstanceID()))
 
Search WWH ::




Custom Search