A variable is a box that stores a value you can change, like a score or a number of lives. Variables are found in the orange Variables category. Making one is the first step to building a real game.
Making a Variable
Click Make a Variable, give it a name like score, and Scratch creates blocks for it. You can choose for all sprites (shared) or for this sprite only (private).
Variable Blocks
- set score to 0 — puts an exact value in the box. Use this to reset at the start.
- change score by 1 — adds to the current value. Use this to score points.
- The variable can be shown on the Stage with a tick box, so players see it.
A Simple Catch Game
Imagine catching falling apples with a basket. Here is the idea:
- When the green flag is clicked, set score to 0.
- The basket sprite uses forever and if key right arrow pressed then change x by 10 to move.
- The apple uses a forever loop to fall down the screen.
- if touching basket then change score by 1 and send the apple back to the top.
Winning and Losing
You can add a rule like if score = 10 then say You win! using an if then block with an equals check from the Operators category. Operators (green blocks) let you compare and do maths, such as =, >, and +.
Remember
- set puts an exact value in a variable; change adds to it.
- Reset the score with set score to 0 at the green flag.
- Use an if then with an Operator like = to check for a win.