Format Numbers
Part of the Building Real Games section of Coddy's Unity journey. Lesson 3 of 60.
A number joined to a string comes out the way C# writes it: a timer shows 12.34567, and a float that is 2 shows 2, with no decimals at all. A format string in ToString() decides how it looks instead. Each 0 in it stands for a digit that is always written: 7.ToString("000") is 007, and 41.27f.ToString("0.0") is 41.3, rounded to one decimal. In string interpolation the same format goes after a colon: $"{coins:000}", $"{topSpeed:0.0} m/s".
Times read better as minutes and seconds. Cast the time to int first, which drops the fraction; then integer division by 60 gives the whole minutes and % 60 the seconds left over. A lap of 83.46 seconds:
float lapTime = 83.46f;
int total = (int)lapTime; // 83
int minutes = total / 60; // 1
int seconds = total % 60; // 23
lapText.text = $"Lap: {minutes}:{seconds:00}"; // Lap: 1:23The 00 keeps two digits: without it, a lap of 64 seconds would read 1:4 instead of 1:04. And because (int) drops the fraction instead of rounding, 59.7 seconds shows as 0:59; rounding would show 0:60 for a moment.
Challenge
EasyFormat the arcade's three numbers.
- In
Update(), first addint seconds = (int)playTime;. - Show the score in six digits,
Score: 000450, with{score:000000}, and the combo with one decimal,Combo: x2.5, with{combo:0.0}. - Show the time as
Time: 2:07:seconds / 60, a colon, thenseconds % 60in two digits.
Press Play and press Space: the score keeps six digits. Then Check.
Try it yourself
using UnityEngine;
using TMPro;
public class Scoreboard : MonoBehaviour
{
public TMP_Text scoreText;
public TMP_Text comboText;
public TMP_Text timeText;
public int score;
public float combo = 1f;
public float playTime;
void Update()
{
playTime += Time.deltaTime;
if (Input.GetKeyDown(KeyCode.Space))
{
score += (int)(100 * combo);
combo += 0.5f;
}
scoreText.text = "Score: " + score;
comboText.text = "Combo: x" + combo;
timeText.text = "Time: " + playTime;
}
}
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