Setting game exit conditions – goals met

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.

Getting ready

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.

How to do it…

  1. Open the runner script in Monodevelop. In the upper section with the variable declaration, modify the declaration for collected, as shown here:
      public int collected, levelGoal;
  2. In the Start() function, add the initialization for levelGoal with the value of 5:
      collected = 0;
      levelGoal= 5;
  3. In the 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!");
      }
  4. If you try the game now, you should see that upon collecting five items, the game stops and the Level complete! message is displayed in the Console.

How it works…

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.67.5