Why is this code not working (If MyVar = 1.0, ...)?


#1

delete


#3

Hi @sj187,

there are two errors in your code. Let me show them to you:

a) When you create the myVar variable, you set its value to string 0, but not the number 0. You see if a variable value is a string by looking at the " " - signs around the 0. A string-value can’t be incremented by the change - block, because it is treated as a text, not a number.

Instead, you can drag and drop the number expression into your variable definition like this:

Now your variable is a proper number and can be treated like one!

b) The second problem in your code is the if - statement that checks for the stored value in the variable. Keep in mind that when you press play, all code you’ve written will run from top to bottom. By the time the code reaches the if - statement, your myVar - variable still holds the number 0 because you have not clicked the Cactus yet.

To check for the value of a variable over time, there are two solutions:

  1. Check for the value when the item is clicked
    24
    Whenever we click the item, we check if myVar is equal to 1

  2. Create a loop that checks the value of the item
    19
    After we’re done with our move, we break out of the loop to end it. Otherwise the loop will repeat forever.

Hope this helps! If you’re interested in learning more about variables and CoBlocks, feel free to take a look at our CoBlocks tutorials -> Working with variables!