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
MediumTell the player when the time runs out first.
- In
Ball.cs'sUpdate(), find the line that logsTime's up!. - 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;
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Physics and Gameplay
1Rigidbody
Gravity and MassPush with AddForceJump with an ImpulseFixedUpdate for PhysicsVelocityKinematic BodiesRecap: Launch Pad4Coroutines
InvokeInvokeRepeating, CancelInvokeYour First CoroutineLoops in CoroutinesStopping CoroutinesRecap: Countdown10Project: Arena Escape
The ArenaHunters2Collisions
OnCollisionEnterWhat Did I Hit?Break on ImpactStanding on the GroundBounce and FrictionCollider ShapesRecap: Breakable Wall5Project: Coin Rush
The Rolling BallCoins to CollectPractice on your own: Unity playground