Variables in Coblocks
Variables are the bread and butter of programs. Without them, it’s hard to make sense of the countless of words and numbers we use to make things fly, run, speak, fall, bounce and dance . Here we explain how variables are used in CoBlocks, and the magic you can create with them!
1. Declaring (creating) variables
To create a variable in CoBlocks, drag & drop the
set variable - block found in the Data->Variables category from the toolbox into your workspace. The default variable name is “myVar”, which you can change to one that suits your needs!
2. Assign a value
Now that you’ve defined your first variable, let’s count some numbers. In the Values - category you can find expression-blocks that we can feed our variable with.
3. Using variable values
We stored a number in our variable. To use it, we take the variable expression block and place it into a statement block
4. Changing variables
You can update the value a variable block holds by using the
set variable - block again. Let’s have our item count how many times it was clicked.
For changing number-values, we can also use the
change variable by - block to get the same result!
5. Tutorial example: Open sesame!
Let’s make a locked door. To unlock it, you need to collect an item first.
1. First, we create a door and a key
2. Let’s open the coding window
Here we define the variable “isLocked” and set it to true.
3. Now we create click - events for each item. Let’s start with the key.
When the key is clicked, we set the variable isLocked to false and remove the key.
4. Let’s add the event for the door
When the door is clicked, we check the isLocked variable. If it is still true (because we did not pick up the key yet) the door won’t open for us. If it is false (because we picked up the key), the door will open!