Menu
CoddyTech

The Score

Lesson 11 of 14 in Coddy's Unity Game: Snake 3D course.

The score counts up in GameManager, but nobody can see it. A TextMeshPro text in the top left corner shows it: a TMP_Text field set in the Inspector, and its text written from code.

Write the text in the same place the number changes, after the change. Then the screen never falls behind the score. A shop updates its coins the same way:

public void Buy(int price)
{
    coins -= price;
    coinsText.text = "Coins: " + coins;
}

Set the text once in Start() too, so the first frame shows the real score whatever the text says in the scene.

challenge icon

Challenge

Medium
  1. In GameManager, add using TMPro; and public TMP_Text scoreText;. The scene sets it to ScoreText, top left.
  2. In Start(), show Score: 0.
  3. In Eat(), show the new score, as Score: 3 after the third food.

Press Play and eat, then press Check.

Try it yourself

using System.Collections.Generic;
using UnityEngine;

public class GameManager : MonoBehaviour
{
    public static GameManager Instance;

    public Snake snake;
    public GameObject foodPrefab;
    private Transform food;
    private int score;

    void Awake()
    {
        Instance = this;
    }

    void Start()
    {
        food = Instantiate(foodPrefab).transform;
        MoveFood();
    }

    public bool IsFood(Vector3 cell)
    {
        return cell == food.position;
    }

    public void Eat()
    {
        score++;
        MoveFood();
    }

    void MoveFood()
    {
        List<Vector3> free = new List<Vector3>();
        for (int x = -snake.edge; x <= snake.edge; x++)
        {
            for (int z = -snake.edge; z <= snake.edge; z++)
            {
                Vector3 cell = new Vector3(x, 0f, z);
                if (!snake.Occupies(cell))
                {
                    free.Add(cell);
                }
            }
        }
        food.position = free[Random.Range(0, free.Count)];
    }
}
quiz iconTest yourself

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

All lessons in Unity Game: Snake 3D