Lesson 6
Keep score
Count your coins and show the number on the screen.
Draft lesson: nobody has followed it from start to finish in the editor yet, so a step may not match what you see.
Video coming soon
We are making a video for this lesson. For now, follow the steps below!
In this lesson you will
- Show words on the screen with Text
- Keep a number while the game runs
- Change the text from code
What you will make
A "Coins: 3" counter that goes up every time you collect a coin.
1. Make the text
- Click GameObject, then Text.
- Name it
Score. - In its Text component, write
Coins: 0. - Put it inside the camera's box, near the top.
Picture coming soonThe Text component in the Inspector
2. Count in the coin script
Open your Coin script. Change onCollisionEnter to this:
onCollisionEnter(other: Collider): void {
if (other.GameObject.Name === 'Player') {
const coins = GameState.Get('coins', 0) + 1;
GameState.Set('coins', coins);
const label = GameObject.Find('Score')?.GetComponent(ComponentType.Text);
if (label) {
label.text = `Coins: ${coins}`;
}
GameObject.Destroy(this.mGameObject);
}
}
Save and Play. Collect some coins!
How does it work?
GameStatekeeps values while the game runs. Every coin can read and change them.GameState.Get('coins', 0)reads the number. If there is none yet, it is0.const coins = ...is a variable: a name for a value.GameObject.Find('Score')finds the GameObject calledScore.`Coins: ${coins}`puts the number inside the words.
Try this
- Count to 10, then show
You win!. Hint:if (coins === 10) { ... } - Give some coins 5 points.
Learn more
More JavaScript The rest of the language your scripts are written in. From MDN.Opens in a new tabTry it here
Your mission
Collect the coins and watch the score go up.
Soon, a small piece of the editor will be right here, so you can practise without leaving the lesson. For now, try it in the editor!