Question

I'm trying to decide which function to call, based on a boolean value.

myBooleanVariable ? function1() : function2();

Unity gives the error :

Expressions in statements must only be executed for their side-effects.

So why does this not work, and how can I make it work ?

Thanks for any help !

Was it helpful?

Solution

So why does this not work, and how can I make it work ?

If it's true that it doesn't work (I don't have Unity to hand), it means UnityScript (Unity's implementation of JavaScript) doesn't support the expression statement. Which puts it at variance with the specification, and means a fair number of JavaScript idioms won't work in it. Your line is perfectly valid JavaScript/ECMAScript. You might check to see if there are "lint"-style options you can enable/disable.

The solution would be to use the result of the expression, or rewrite that using if.

Use the result:

var f = myBooleanVariable ? function1() : function2();

Using if:

if (myBooleanVariable) {
    function1();
}
else {
    function2();
}

Or if you really want the if to be on one line:

if (myBooleanVariable) function1(); else function2();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top