Game Development Reference
In-Depth Information
This timer is very simple. It doesn't require any GUI printout, so for it, you will use a yield . Using
yield in C# is a lot more complicated than in JavaScript, but it is a very handy thing to know how
to do. Yield sets a pause before the lines of code following it are evaluated. Most code is evaluated
in a linear fashion: b follows a , c follows b , etc. A coroutine does not pause the evaluation of the
functions; it merely delays what happens after the time has elapsed, by running in conjunction with
the rest of the code until it has finished. To call it from any function, you must use StartCoroutine() .
The function it calls from there is an iEnumerator. You will let the Gnomatic Garden Defender do
his job for 25-30 seconds before the zombie bunnies start multiplying. Once they start multiplying,
they will multiply every 10-15 seconds thereafter. In case you are wondering if there will be any way
to stop the ravening hoards from reproducing and overrunning the garden and the world, you will
create a flag, canReproduce , that will be able to stop the vicious cycle!
1.
Create a new variable to store the rate of reproduction:
float reproRate = 12f; // base time before respawning
In the Start function, after the call to PopulateGardenBunnies , add the
following:
2.
float tempRate = reproRate * 2; // allow extra time before the first drop
StartCoroutine(StartReproducing(tempRate)); // start the first timer; pass in reproRate
seconds
The first respawn is longer to give the player time to settle in. It uses a temporary variable, local to
the Start function, derived from the regular reproduction rate. It may seem like a lot of extra work to
add variables instead of hard-coding numbers, but if you wanted to make things easier or harder for
the player, just as with the litterSize , you would have to change the reproRate in only one place.
And now create the StartReproducing() iEnumerator (a different kind of
function):
3.
IEnumerator StartReproducing(float minTime) {
// wait for this much time before going on
float adjustedTime = Random.Range(minTime, minTime + 5f);
yield return new WaitForSeconds(adjustedTime);
// having waited, make more zombie bunnies
PopulateGardenBunnies (litterSize);
//and start the coroutine again to minTime, but only if there are enough left to reproduce...
if (canReproduce) StartCoroutine(StartReproducing(reproRate));
}
4.
Up with the variable declarations, add the flag to control the reproduction:
bool canReproduce = true; // flag to control reproduction of zombie bunnies
5.
Save the script.
6.
Click Play, and sit back and watch the show.
The zombie bunnies quickly overrun the garden (Figure 7-34 ).
 
Search WWH ::




Custom Search