Adding in Score/High score

Now that the game has the start and ending, let's make it so that we can gain a score whenever we hit a duck:

  1. From the Hierarchy tab, duplicate the Time Text object and rename it to Score Text. Go to the Rect Transform's Anchor Presets menu, hold down Alt + Shift, and click on the top-left option. Then, change Pos X to 10 and Pos Y to -10 to push it a bit off from the edge of the screen.
  2. Then, in the Text component, change the Horizontal alignment to the left and change the Text to Score 0.
  3. Finally, change the Outline component's Effect Distance to 1.5, -1.5:
    Adding in Score/High score
  4. Next, we will want to duplicate the Score Text object and rename it High Score Text. From there, open up the Anchor Presets menu, hold down Alt + Shift, and click on the top-right option. Afterwards, change Pos X to -10 and Pos Y to -10.
  5. Afterwards, in the Text component, change the Text to High Score 0. Then, change the Alignment to the right side:
    Adding in Score/High score

    Now that we have the objects created, let's add in the functionality for scoring using what we already know and PlayerPrefs for the high score.

    PlayerPrefs allow us to store small amounts of data on the end user's machine. Using PlayerPrefs is a great way to save data for user levels, the coordinates of where enemies are, or a high score so when the user comes back to the game, it will show the highest score achieved over the course of all games played.

  6. Open up the GameController script and from there, add in the following variables:
        private int score;
        public Text scoreText;
        public Text highScoreText;
  7. Now in the Start function, add in the following bolded code:
        // Use this for initialization
        void Start ()
        {
            iTween.ValueTo(gameObject, iTween.Hash(
                            "from", timeLeft,
                            "to", 0,
                            "time", timeLeft,
                            "onupdatetarget", gameObject,
                            "onupdate", "tweenUpdate",
                            "oncomplete", "GameComplete"
                            ));
            StartCoroutine("SpawnTargets");
    
            highScoreText.text = "High Score: " + PlayerPrefs.GetInt("highScore").ToString();
            score = 0;
        }

PlayerPrefs

As I mentioned previously, the PlayerPrefs class allows us to save small parts of data on our player's computers for retrieval later. The PlayerPrefs can store the following types: float, int, and string. There are two key functions for each of the types Get and Set with the type added afterwards (GetFloat, SetString, and so on).

Set

The Set functions take in two parameters—the first being a string and the second being of the type you're trying to set. This will save the value in the second parameter to the registry on our computer with the string as a reference for us to get the data back with the Get function.

If there was a value previously saved with that variable name, it will be overwritten with the new value.

Note

To be sure that your variables do not get overwritten by other projects, it's important to make sure that you set the Product Name and Company Name in the Project Settings.

Get

The Get functions will retrieve the value that it currently has set, if there is one. If it cannot find a value (that variable doesn't exist yet), it will return 0, or whatever you put in as the second parameter. So as an example, I could do something like this:

void Start() 
{
        print(PlayerPrefs.GetString("Player Name", "Bob"));
}

Then, if there already is a value assigned for Player Name, it will print out that, but otherwise, it will give you the value of Bob. This is great if you want to have a default value other than 0 or an empty string "".

Depending on what operating system you're currently using for this project or are porting to the location of where the values are saved to are different. For these locations, or for more information on the PlayerPrefs class, check out http://docs.unity3d.com/ScriptReference/PlayerPrefs.html.

Next, we need to create the functionality for hitting something, so add in the following function:

public void IncreaseScore()
{
    score++;
    scoreText.text = "Score: " + score.ToString();

    if (score > PlayerPrefs.GetInt("highScore"))
    {
        PlayerPrefs.SetInt("highScore", score);
        highScoreText.text = "High Score: " + score.ToString();
    }
}

Finally, we need to call the function, so go into the TargetBehaviour script and add in the following bolded line:

    /// <summary>
    /// Called whenever the player clicks on the object.
    /// Only works if you have a collider
    /// </summary>
    void OnMouseDown()
    {
        // Is it valid to hit it
        if (!beenHit && activated)
        {
            GameController._instance.IncreaseScore();
            beenHit = true;
            animator.Play("Flip");

            StopAllCoroutines();

            StartCoroutine(HideTarget());
        }
    }

Save both of your scripts and go back into the Unity editor. Select the Game Controller object and assign the Score Text and High Score Text variables to their respective game objects:

Get

Save your project and run the game!

Get

As you can see, when you play the game and exceed the high score, it will save that value and update the high score text. In addition, when you restart the game, your high score is saved! Excellent!

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

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