Menu
CoddyTech

Survive and Score

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 80 of 85.

This step finishes Dodge the Blocks: a timer that spawns, a list that moves and cleans up, a hit test, and a score that counts the seconds. (int) in front of a float drops its fraction.

challenge icon

Challenge

Medium

Add a score, and blocks that fall faster and faster.

  1. Add private float score; and [SerializeField] private float speedUp = 0.2f;.
  2. At the top of Update(), add Time.deltaTime to score and speedUp * Time.deltaTime to fallSpeed.
  3. On a hit, log "Game over! Score: " + (int)score. (int) drops the fraction: 12.7 shows as 12.

Press Play and survive: a hit logs 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 -= spawnEvery;
            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);
            }
        }
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Unity Scripting Basics

Practice on your own: Unity playground