Show the Score
Part of the Building Real Games section of Coddy's Unity journey. Lesson 2 of 60.
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
EasyShow the gardener's seeds and trees on screen.
- In
Gardener.cs, writevoid ShowCounts()that setsseedsText.textto"Seeds: " + seedsandtreesText.textto"Trees: " + trees. - Call it in a new
Start(), and in the plantingifaftertrees++;.
Press Play: the texts read Seeds: 5 and Trees: 0, and change with every sapling. 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
}
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 SwapPractice on your own: Unity playground