Three Lives
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 41 of 67.
Challenge
MediumThree 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 overand turn the script off withenabled = false. Unity stops callingUpdate()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
1Your First Script
Hello, UnityPlace the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube4Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot7Project: Catch the Star
The CatcherA Falling Star5Transforms and Hierarchy
Parents and ChildrenScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon