Game Development Reference
In-Depth Information
27
28 //Is player input allowed
29 public bool InputAllowed = true;
30 //-----------------------------------------
31 // Use this for initialization
32 void Awake ()
33 {
34 //Check if existing instance of class exists in scene
35 //If so, then destroy this instance
36
if(instance)
37
{
38
DestroyImmediate(gameObject);
39
return;
40
}
41
42
//Make this active and only instance
43
instance = this;
44
45 //Make game manager persistent
46 DontDestroyOnLoad(gameObject);
47 }
48 //-----------------------------------------
49 }
50 //-----------------------------------------
The following are the comments on the code sample 3-14:
•
Lines 10-20
: A private member
instance
is added to the
Manager
class,
which is declared as
static
. This means the variable is shared across all
instances of the class if there are multiple instances, as opposed to being
a variable whose value is specific to each instance. This allows each new
instance, when created, to determine whether there is any existing instance
of the class in memory. This variable is made publically accessible too via the
Instance
property, which only has a
get
member to make it read-only.
•
Lines 36-43
: Here, in the
Awake
event (called at object creation), the instance
variable is checked to see whether any valid instance of the class exists in the
current scene already. If it does, then the current object is deleted, because
only one instance of this class is allowed and already exists. This means the
GameManager
will persist across scene changes, and there will always be only
one original instance of the object in the scene.