Game Development Reference
In-Depth Information
So we've now created a singleton Game Manager class that exposes a Notifications Manager property
to which all objects may send and receive application-wide event notifications, if they need to. Let's
put these classes to the test in a practical context for CMOD. To prepare for this process in the Unity
Editor, first ensure an empty GameObject is created in the scene. I've named it GameManager . This
object should contain both a GameManager and a NotificationsManager component. Remember, due to
the RequiresComponent keyword, you don't need to add both components manually. You can just add
a GameManager component to an object, and Unity automatically adds a NotificationsManager if
one doesn't already exist. Having done this, our scene is configured for using the GameManager as a
globally accessible Singleton. We'll see how to use it in the next section.
Completing the Cash Power-Up
Back in Listing 4-12, we coded a Cash Power-Up object to respond directly to an OnTriggerEnter event,
to handle player collisions. However, we also need this event to integrate with NotificationsManager
to notify all listener objects, in case they, too, need to respond when it happens. In other words,
the event OnTriggerEnter of Powerup_Dollar needs to be amended to post a notification to the
NotificationsManager. In this context, the NotificationsManager is accessible as a static member
variable of the globally accessible GameManager singleton. Consider the completed Powerup_Dollar
class in Listing 4-17, which posts an event notification.
Listing 4-17. Completed Cash Power-Up
01 //-------------------------------------------------------------
02 using UnityEngine;
03 using System.Collections;
04 //--------------------------------------------------------------
05 public class Powerup_Dollar : MonoBehaviour
06 {
07 //Amount of cash to give player
08 public float CashAmount = 100.0f;
09
10 //Audio Clip for this object
11 public AudioClip Clip = null;
12
13 //Audio Source for sound playback
14 private AudioSource SFX = null;
15 //--------------------------------------------------------------
16 void Start()
17 {
18 //Find sound object in scene
19 GameObject SoundsObject = GameObject.FindGameObjectWithTag("sounds");
20
21 //If no sound object, then exit
22 if(SoundsObject == null) return;
23
24 //Get audio source component for sfx
25 SFX = SoundsObject.GetComponent<AudioSource>();
26 }
27 //--------------------------------------------------------------
28 //Event triggered when colliding with player
 
Search WWH ::




Custom Search