Skip to content
LessonItem 1 of 30

What Is a Variable? Learning from an Independence Day Scoreboard

You are viewing a preview. Enroll to save your progress.

In your previous Scratch class you made sprites move, talk, and change costumes. Now we will learn something that makes games feel alive: variables.

An example from an Independence Day contest

Imagine a tug of war between class 5A and class 5B. At the front there is a whiteboard that says "Score 5A" and "Score 5B". Every time a class wins a round, the teacher wipes the old number and writes a new one. The board has a name (Score 5A) and a value (for example 2). The value can change, but the name stays the same.

That is a variable: a storage box with a name that holds one value. The computer can read the value and replace it at any time.

How a variable works, step by step

  1. Give it a name that is clear, for example score, lives, or jumps.
  2. Set a starting value, usually 0 when the game starts.
  3. Change the value when something happens, for example add 1.
  4. Read the value to show it or to make a decision.

Variables in Scratch 3

Open the Variables category (orange), then click the Make a Variable button. Type a name, then choose For all sprites (every sprite may use it) or For this sprite only (only one sprite). For a score, choose For all sprites.

Once it is made, new blocks appear:

  • set score to 0 gives it an exact value.
  • change score by 1 adds to it (or subtracts, if the number is negative, such as -1).
  • show variable and hide variable show or hide the number box on the stage.

A simple example script:

Text
when green flag clicked
set [score] to 0
show variable [score]

when this sprite clicked
change [score] by 1

Every time you click the sprite, the number on the stage goes up by one. When the green flag is clicked again, the score goes back to 0. This is why we always set a starting value: so the game starts fairly, just like a scoreboard wiped clean before a new contest.

Tip: if your Scratch is in Indonesian, the blocks are called atur, ubah, and Buat Variabel. Change the language with the globe icon at the top left.