Game Development Reference
In-Depth Information
28 DestroyImmediate(gameObject); //Delete duplicate
29 else
30 {
31 instance = this; //Make this object the only instance
32 DontDestroyOnLoad (gameObject); //Set as do not destroy
33 }
34 }
35 }
Note
There are many ways to check for equality between objects, to determine if two references to an
object refer to one and the same object. You can use
==
equality, but I prefer
Object.GetInstanceID
.
The ID for each instance is
guaranteed
to be unique for a single session (see Unity documentation).
Finally, after Listing 4-15, the Singleton magic is completed, and we're left with a Singleton object.
Listing 4-15 adds an
Awake
event, which is called for the instance automatically by Unity on object
creation (before the
Start
function). Inside this function we test the private static member
instance
to see if an active instance of this object already exists, and if it does, we
delete
the current instance
(lines 27 and 28), since it must be a duplicate. Notice, in this case we don't simply hide or deactivate
the object, as we did when hiding the cash power-up when collected in Listing 4-12. Here, we
really do delete the object, if required, using the API function
DestroyImmediate
, restricting the
active instance to just one. And that's it! Here, we've created a singleton GameManager. To test,
I recommend adding this class as a component to an empty GameObject in the scene, and then
see what happens you try to instantiate more instances in script, using the
new
keyword or the
AddComponent
function. It shouldn't be possible, thanks to the Singleton functionality (see Figure
4-12
).
Figure 4-12.
Adding the GameManager component as a Singleton to an empty GameObject