Menu
CoddyTech

Win or Lose

Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 32 of 63.

challenge icon

Challenge

Medium

Last step: a way to win. Keep everything from the earlier steps, and add to Ball:

  • public int target = 10; (the Inspector sets 8).
  • The game is on while timeLeft is above 0 and score is below target. Write that as a method, bool IsPlaying(), and use it: the clock counts down, the arrows push and coins add to the score only while the game is on.
  • When a coin brings score up to target or more, log You win! after the score line.
  • When the time runs out first, log You lose! after the Time's up! line.

Press Play and reach 8 points before the clock runs out, 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;
    private Rigidbody rb;

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

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

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

    public void AddScore(int points)
    {
        score += points;
        Debug.Log("Score: " + score);
    }
}

All lessons in Physics and Gameplay