Menu
CoddyTech

Three Lives

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 55 of 85.

This step finishes Catch the Star: a game that moves, scores, speeds up and ends, all in one script. enabled = false turns a script off, and Unity stops calling its Update().

challenge icon

Challenge

Medium

Three misses end the game.

  1. Add [SerializeField] private int lives = 3;.
  2. In the miss's else if, subtract 1 from lives and log "Missed! Lives: " + lives.
  3. Then, when lives == 0, log Game over and set enabled = false;, which stops Update().

Press Play and miss three stars: the Console shows Game over and the game stops. Then Check.

Try it yourself

using UnityEngine;

public class Catcher : MonoBehaviour
{
    [SerializeField] private float speed = 6f;
    [SerializeField] private Transform star;
    [SerializeField] private float fallSpeed = 3f;
    [SerializeField] private float speedUp = 0.5f;
    private int score;

    void Update()
    {
        float x = transform.position.x;
        if (Input.GetKey(KeyCode.RightArrow))
        {
            x += speed * Time.deltaTime;
        }
        if (Input.GetKey(KeyCode.LeftArrow))
        {
            x -= speed * Time.deltaTime;
        }
        x = Mathf.Clamp(x, -4f, 4f);
        transform.position = new Vector3(x, transform.position.y, transform.position.z);

        star.position += Vector3.down * fallSpeed * Time.deltaTime;

        if (Vector3.Distance(transform.position, star.position) < 1f)
        {
            score++;
            fallSpeed += speedUp;
            Debug.Log("Caught! Score: " + score);
            ResetStar();
        }
        else if (star.position.y < 0f)
        {
            ResetStar();
        }
    }

    void ResetStar()
    {
        star.position = new Vector3(Random.Range(-4f, 4f), 6f, 0f);
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Unity Scripting Basics

Practice on your own: Unity playground