Menu
CoddyTech

Three Lives

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 41 of 67.

challenge icon

Challenge

Medium

Three misses end the game. Add [SerializeField] private int lives (the scene sets it to 3).

  • Each missed star costs a life and logs Missed! Lives: 2, with the lives left.
  • When lives reach 0, also log Game over and turn the script off with enabled = false. Unity stops calling Update() on a disabled script, so the star stops and the catcher no longer moves.

Catches still score and speed the stars up. Keep everything from the earlier steps.

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);
    }
}

All lessons in Unity Scripting Basics