Menu
CoddyTech

You Lose

Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 34 of 71.

This step finishes Coin Rush: a ball pushed by forces, coins that are triggers, a score kept by one script and a clock that ends the game.

challenge icon

Challenge

Medium

Tell the player when the time runs out first.

  1. In Ball.cs's Update(), find the line that logs Time's up!.
  2. Right after it, log You lose!.

Press Play and let the clock run out: the Console shows Time's up! Score: 0, then You lose!. Then Check.

Try it yourself

using UnityEngine;

public class Ball : MonoBehaviour
{
    public float force = 10f;
    public int score;
    public float timeLimit = 60f;
    public float timeLeft;
    public int target = 10;
    private Rigidbody rb;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
        timeLeft = timeLimit;
    }

    void Update()
    {
        if (IsPlaying())
        {
            timeLeft -= Time.deltaTime;
            if (timeLeft <= 0f)
            {
                timeLeft = 0f;
                Debug.Log("Time's up! Score: " + score);
            }
        }
    }

    void FixedUpdate()
    {
        if (IsPlaying())
        {
            float x = Input.GetAxis("Horizontal");
            float z = Input.GetAxis("Vertical");
            rb.AddForce(new Vector3(x, 0f, z) * force);
        }
    }

    public void AddScore(int points)
    {
        if (!IsPlaying())
        {
            return;
        }
        score += points;
        Debug.Log("Score: " + score);
        if (score >= target)
        {
            Debug.Log("You win!");
        }
    }

    bool IsPlaying()
    {
        return timeLeft > 0f && score < target;
    }
}
quiz iconTest yourself

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

All lessons in Physics and Gameplay

Practice on your own: Unity playground