Show the Score
Part of the Building Real Games section of Coddy's Unity journey. Lesson 2 of 56.
A text's text is a string, so a number has to become text before it is shown. Joining it to a string with + does that: "Wood: " + wood is Wood: 12 when wood is 12, and wood.ToString() is 12. The int on its own does not fit: woodText.text = wood; fails with CS0029, Cannot implicitly convert type 'int' to 'string'.
The number lives in an int field, and the text only shows it. One method rewrites the text from the field; every change to the number calls it, and so does Start(), so the first frame shows the real value instead of what was typed in the Inspector. Here Space chops 3 logs:
public TMP_Text woodText;
private int wood;
void Start()
{
ShowWood();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
wood += 3;
ShowWood();
}
}
void ShowWood()
{
woodText.text = "Wood: " + wood;
}The text changes only when wood does. Rewriting it in every Update() would look the same, but it would build a new string 60 times a second for nothing. The order matters: ShowWood() called before wood += 3 would show the old count, one press behind.
Challenge
EasyThe gardener plants trees. The arrows walk it and Space plants a sapling while there are seeds left, as Gardener.cs already does. Show the counts on screen; the scene links seedsText and treesText:
seedsTextshows the seeds left, asSeeds: 4, andtreesTextthe trees planted, asTrees: 1.- Both are right from the first frame and after every planting. The Inspector gives the gardener 5 seeds, though the texts in the scene still say
Seeds: 10andTrees: ?. - Write one method that sets both texts, and call it wherever it is needed.
Press Play, plant until the seeds run out, then Check.
Try it yourself
using UnityEngine;
using TMPro;
public class Gardener : MonoBehaviour
{
public float speed = 4f;
public int seeds = 10;
public GameObject saplingPrefab;
public TMP_Text seedsText;
public TMP_Text treesText;
private int trees;
void Update()
{
float move = Input.GetAxisRaw("Horizontal");
transform.Translate(move * speed * Time.deltaTime, 0f, 0f);
if (Input.GetKeyDown(KeyCode.Space) && seeds > 0)
{
Vector3 spot = new Vector3(transform.position.x, 0.5f, 1.5f);
Instantiate(saplingPrefab, spot, Quaternion.identity);
seeds--;
trees++;
}
}
// Show Seeds: and Trees: in the two texts, from the first frame on
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Building Real Games
2Buttons and Screens
Buttons and onClickLambdasWiring in the InspectorPanels On and OffHealth BarsRecap: Upgrade Shop5Saving with PlayerPrefs
Save a NumberLoad with a DefaultHigh ScoreSave SettingsRecap: Coins in the Bank3The Game Manager
One Script Runs the GameThe SingletonGame StatesSwitching on the StateRecap: Round Manager6Project: Endless Runner
Three LanesObstacles Ahead9The New Input System
Two Input SystemsKeyboard and MousePressed This FrameInput ActionsRecap: Input Swap