Saving and loading player data – using static properties

Keeping track of the player's progress and user settings during a game is vital to give your game a greater feel of depth and content. In this recipe, we will learn how to make our game remember the player's score between the different levels (scenes).

Getting ready

We have included a complete project in a Unity package named game_HigherOrLower in the 1362_10_04 folder. In order to follow this recipe, we will import this package as the starting point.

How to do it...

To save and load player data, follow these steps:

  1. Create a new 2D project and import the game_HigherOrLower package.
  2. Add each of the scenes to the build in the sequence (scene0_mainMenu, then scene1_gamePlaying, and so on).
  3. Make yourself familiar with the game by playing it a few times and examining the contents of the scenes. The game starts on the scene0_mainMenu scene, inside the Scenes folder.
  4. Let's create a class to store the number of correct and incorrect guesses made by the user. Create a new C# script called Player with the following code:
    using UnityEngine;
    
    public class Player : MonoBehaviour {
      public static int scoreCorrect = 0;
      public static int scoreIncorrect = 0;
    }
  5. In the lower-left corner of the scene0_mainMenu scene, create a UI Text GameObject named Text – score, containing the placeholder text Score: 99 / 99.
    How to do it...
  6. Next, attach the following C# script to UI GameObject Text – score:
    using UnityEngine;
    using System.Collections;
    
    using UnityEngine.UI;
    
    public class UpdateScoreText : MonoBehaviour {
      void Start(){
        Text scoreText = GetComponent<Text>();
        int totalAttempts = Player.scoreCorrect + Player.scoreIncorrect;
        string scoreMessage = "Score = ";
        scoreMessage += Player.scoreCorrect + " / " + totalAttempts;
    
        scoreText.text = scoreMessage;
      }
    }
  7. In the scene2_gameWon scene, attach the following C# script to the Main Camera:
    using UnityEngine;
    
    public class IncrementCorrectScore : MonoBehaviour {
      void Start () {
        Player.scoreCorrect++;	
      }
    }
  8. In the scene3_gameLost scene, attach the following C# script to the Main Camera:
    using UnityEngine;
    
    public class IncrementIncorrectScore : MonoBehaviour {
      void Start () {
        Player.scoreIncorrect++;	
      }
    }
  9. Save your scripts and play the game. As you progress from level (scene) to level, you will find that the score and player's name are remembered, until you quit the application.

How it works...

The Player class uses static (class) properties scoreCorrect and scoreIncorrect to store the current total number of correct and incorrect guesses. Since these are public static properties, any object from any scene can access (set or get) these values, since the static properties are remembered from scene to scene. This class also provides the public static method called ZeroTotals() that resets both the values to zero.

When the scene0_mainMenu scene is loaded, all the GameObjects with scripts will have their Start() methods executed. The UI Text GameObject called Text – score has an instance of the UpdateScoreText class as s script component, so that the scripts Start() method will be executed, which retrieves the correct and incorrect totals from the Player class, creates the scoreMessage string about the current score, and updates the text property so that the user sees the current score.

When the game is running and the user guesses correctly (higher), then the scene2_gameWon scene is loaded. So the Start() method, of the IncrementCorrectScore script component, of the Main Camera in this scene is executed, which adds 1 to the scoreCorrect variable of the Player class.

When the game is running and the user guesses wrongly (lower), then scene scene3_gameLost is loaded. So the Start() method, of the IncrementIncorrectScore script component, of the Main Camera in this scene is executed, which adds 1 to the scoreIncorrect variable of the Player class.

The next time the user visits the main menu scene, the new values of the correct and incorrect totals will be read from the Player class, and the UI Text on the screen will inform the user of their updated total score for the game.

There's more...

There are some details that you don't want to miss.

Hiding the score before the first attempt completed

Showing a score of zero out of zero isn't very professional. Let's add some logic so that the score is only displayed (a non-empty string) if the total number of attempts is greater than zero:

void Start(){
  Text scoreText = GetComponent<Text>();
  int totalAttempts = Player.scoreCorrect + Player.scoreIncorrect;

  // default is empty string
  string scoreMessage = "";
  if( totalAttempts > 0){
    scoreMessage = "Score = ";
    scoreMessage += Player.scoreCorrect + " / " + totalAttempts;
  }

  scoreText.text = scoreMessage;
}

See also

Refer to the following recipe in this chapter for more information:

  • Saving and loading player data – using PlayerPrefs
..................Content has been hidden....................

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