To set the winning conditions for the level, we need to count the items collected and check that value against a default number of items we want the level to end with. Once the number of items collected equals the goal, the player receives a message.
This is the topic of our next recipe.
We have already counted the number of items collected in the runner
script, through the collected
int
variable. Thus we can take advantage of the code we already implemented and improve it to manage the additional functionality.
runner
script in Monodevelop. In the upper section with the variable declaration, modify the declaration for collected
, as shown here:public int collected, levelGoal;
Start()
function, add the initialization for levelGoal
with the value of 5
:collected = 0; levelGoal= 5;
Update()
function, add the following lines to check whether the winning conditions are met, and send a message to the player if they are met:if(collected == levelGoal){ Time.timeScale = 0; Debug.Log("level complete!"); }
The logic is pretty easy here; whenever the player collects an item, the number of total items collected is increased by one. When this number equals the goal value we set for the level, the game ends.
In this book, we will gradually work to improve the feedback provided for the player and the game flow.
3.139.67.5