Survive and Score
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 64 of 67.
Challenge
MediumLast step: a score, and a game that gets harder. Keep everything from the earlier steps, and add:
- A
floatnamedscorethat counts the seconds survived: add the frame's time to it on every frame while the game runs. - A field
speedUpthat the Inspector sets (0.2).fallSpeedgrows byspeedUpevery second, a little on every frame, so the blocks fall faster and faster. - On a hit, log
Game over! Score: 12instead ofGame over, with the whole seconds ofscore(cast it to anint).
Press Play and beat your score, then Check.
Try it yourself
using System.Collections.Generic;
using UnityEngine;
public class Runner : MonoBehaviour
{
[SerializeField] private float speed = 6f;
[SerializeField] private float laneEdge = 4f;
[SerializeField] private GameObject blockPrefab;
[SerializeField] private float spawnEvery = 1f;
[SerializeField] private float fallSpeed = 5f;
private List<GameObject> blocks = new List<GameObject>();
private float timer;
void Update()
{
Vector3 p = transform.position;
p.x += Input.GetAxisRaw("Horizontal") * speed * Time.deltaTime;
p.x = Mathf.Clamp(p.x, -laneEdge, laneEdge);
transform.position = p;
timer += Time.deltaTime;
if (timer >= spawnEvery)
{
timer = 0f;
Vector3 spot = new Vector3(Random.Range(-laneEdge, laneEdge), 10f, 0f);
blocks.Add(Instantiate(blockPrefab, spot, Quaternion.identity));
}
for (int i = blocks.Count - 1; i >= 0; i--)
{
blocks[i].transform.position += Vector3.down * fallSpeed * Time.deltaTime;
Vector3 b = blocks[i].transform.position;
if (Mathf.Abs(b.x - transform.position.x) < 1f && Mathf.Abs(b.y - transform.position.y) < 1f)
{
Debug.Log("Game over");
enabled = false;
return;
}
if (b.y < -1f)
{
Destroy(blocks[i]);
blocks.RemoveAt(i);
}
}
}
}
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