Game Development Reference
In-Depth Information
1.
Create a new Empty GameObject, and name it Game Manager .
2.
Create a new C# Script, and name it ScoreKeeper .
3.
Drag the new script onto the Game Manager object.
4.
Add the following variable to it:
int currentBunCount = 0; // the current number of zombie bunnies
5.
Add a little function to keep track of the count:
void UpdateCount (int adjustment) {
currentBunCount += adjustment; // add or subtract the number passed in
print ("new count: " + currentBunCount);
}
6.
Save the script.
7.
Open the SpawnBunnies script.
8.
Add the following variable:
GameObject gameManager; // the master repository for game info
Find and assign it in the Start function, above the PopulateGardenBunnies line:
9.
gameManager = GameObject.Find("Game Manager"); // identify and assign the Game Manager object
If you put the line below the StartCoroutine line, it may not get evaluated in time.
To update the count, you will use SendMessage to tell the UpdateCount function on the other script
how many to add. Communication between scripts is a key concept in Unity, and there are many
different ways to achieve it. SendMessage() will find the function on any of the gameObject's scripts,
but it can pass only one argument.
In the PopulateGardenBunnies function, replace the currentBunCount += count
line with the following:
10.
// send the amount to update the total
gameManager.SendMessage("UpdateCount",count, SendMessageOptions.DontRequireReceiver);
The SendMessage function calls a function—in this case, UpdateCount —on any script on the contacted
gameObject—in this case, the Game Manager. It has the option to send one argument—in this case,
count . The last part, also optional, tells it not to report back to you via the console if a receiver can't
be found. You've already added a print statement to the UpdateFunction , so you will know when it
has been called. If you do not see results from a SendMessage , it is often a good idea to require it to
report back to the console if it can't find a receiver. Simply remove the Dont .
 
Search WWH ::




Custom Search