Menu
CoddyTech

You Win

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

challenge icon

Challenge

Medium

Let the player win at target points.

  1. In Ball.cs, add public int target = 10; and bool IsPlaying(), returning timeLeft > 0f && score < target.
  2. Use IsPlaying() instead of timeLeft > 0f in Update() and FixedUpdate(), and start AddScore with if (!IsPlaying()) return;.
  3. After the score line, when score >= target, log You win!.

Press Play and collect 8 points. 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

Practice on your own: Unity playground