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
MediumShow the score on screen.
- In
GameManager, addusing TMPro;andpublic TMP_Text scoreText;(the scene links ScoreText). - In
Start(), showScore: 0. - In
Eat(), after the point, show"Score: " + score.
Press Play and eat: the top left counts Score: 1, Score: 2. Then 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)];
}
}
All lessons in Unity Game: Snake 3D
Practice on your own: Unity playground