Variables and Keeping Score
💻 ScratchCreate variables, change them during a game and display a live score.
A variable is a named box that holds a value. In a game it can store the score, lives, time or level.
- Create a variable in Scratch.
- Change a variable with blocks.
- Show a variable on the stage.
Make a Variable
Open the Variables category and click Make a Variable. Name it score. Make sure it is available for all sprites if every sprite needs to read it.
Change the Score
When the player catches a falling apple, increase the score by one. Use a when green flag clicked block to set the score to zero at the start, then add one inside the collision check.
when green flag clicked
set [score v] to [0]
when I receive [catch apple v]
change [score v] by (1)Show It on Stage
Tick the checkbox beside the variable to show it on the stage. You can drag the display to a corner. For a cleaner look, use a say block joined with the score.
Practice
- Create a variable called lives and set it to 3 at the start.
- Subtract one life when the sprite touches a danger colour.
- Show the score on the stage and move the display to the top-left corner.
Hands-on exercise
Build a small catching game.
1. Create a variable named score.
2. Set score to 0 when the green flag is clicked.
3. Increase score by 1 whenever the catcher touches the falling object.
4. Reset the object to the top after each catch.
Recap
Variables store values that can change. Set them at the start, update them during play and show them when the player needs to see them.
Example
when green flag clicked
set [score v] to [0]
when I receive [catch apple v]
change [score v] by (1)
Exercises
1. Create a variable named score.
2. Set score to 0 when the green flag is clicked.
3. Increase score by 1 whenever the catcher touches the falling object.
4. Reset the object to the top after each catch.
Expected Output
The score increases by one each time the catcher touches the falling object.
Lesson Nav
Scratch Course
0/9 lessons completed
- 1 Your First Scratch Project Concept
- 2 Motion and Looks Blocks Tutorial
- 3 Events and Repeat Loops Tutorial
- 4 Your First Scratch Game Project
- 5 Variables and Keeping Score Tutorial
- 6 Making Decisions with Conditions Tutorial
- 7 Sensing, Input and Operators Tutorial
- 8 Clones, Timers and Levels Tutorial
- 9 Project: Build a Story Game Project