Controlling which game to play

We can now make the GameController responsible for choosing and switching which games to play. We'll randomly pick a new ball game after each throw.

The GameController will be populated with the list of ball games, subscribe to their events, and then decide to activate or deactivate ones. Modify the script as follows:

File: GameController.cs

Replace ballGame with a list of ballGames, the current game index, and add a Boolean to ensure we initialize only once:

    public BallGame[] BallGames;

private int currentGameIndex; private bool isInitialized;

Then, add this code to Start():

        for (int i = 0; i < BallGames.Length; i++) { 
            BallGames[i].OnGoalWon.AddListener(WonGoal); 
            BallGames[i].OnGoalLost.AddListener(LostGoal); 
            BallGames[i].Deactivate(); 
        } 
 
        isInitialized = true; 

The following helper method will choose and activate a random game:

    private void SetRandomGame() { 
        //clears the last game 
        BallGames[currentGameIndex].Deactivate(); 
        //sets a new game 
        currentGameIndex = Random.Range(0, BallGames.Length); 
        BallGames[currentGameIndex].Activate(); 
    } 

Then, the random game gets selected when the app starts and each time the player gets a goal:

    public void StartGame() { 
        SetRandomGame(); 
    } 
 
    void WonGoal() { 
        ChangeScore(hitPoints); 
        SetRandomGame(); 
    } 
    private void OnEnable() { 
        if (isInitialized) 
            SetRandomGame(); 
    } 

Back in Unity, we can now finish wiring up the controller and state manager:

  1. Select the GameController in Hierarchy.
  2. Unfold Ball Games and set Size to 4 (or the number of games you are using).
  3. Then populate the list of Ball Games from the ball games in the scene Hierarchy.
  4. Select AppStateManager, click + to add to the OnStartGame list, drag GameController onto the Object slot, and select the GameController.StartGame function.

There you have it! Our ball game is now a robust app that has multiple level variations.

Play it now. Build and run it for your Android device. You can follow instructions from earlier in the book to also build it for iOS mobile devices. Show it to your friends and family. Have a ball!

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

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