- Home /
Unity/Javascript Operators
I am trying to use an 'or' operator in an if statement, and Unity is telling me it's an unexpected token.
What does Unity recognize as an 'or' operator? Found little in the script ref.
Thank you for the help!
Answer by Jessy · Jun 16, 2010 at 02:06 AM
You use two vertical "pipes" for or.
||
http://www.w3schools.com/JS/js_comparisons.asp
It's nice, because it "short circuits". That is, if the first statement is true, it won't bother to evaluate any more statements. So if you have a statement that is likely to be true most of the time, more so than another statement, put that first for more efficient code.
Ah, so I did have it right. What did I do wrong then?
if(Input.GetAxis("P1_HorizontalAim")) || (Input.GetAxis("P1_VerticalAim")) { isTurning = true; }
if(Input.GetAxis("P1_HorizontalAim") || Input.GetAxis("P1_VerticalAim")) { isTurning = true; }
Answer by Cyclops · Jun 16, 2010 at 02:28 AM
What you currently have is:
if (Input.GetAxis("P1_HorizontalAim")) || (Input.GetAxis("P1_VerticalAim")) {
isTurning = true;
}
First, the entire conditional part of the if state needs to be in parentheses. Second, I suspect that Javascript wants a boolean value in the if - and Input is returning a float. Try this instead:
if ((Mathf.Abs(Input.GetAxis("P1_HorizontalAim")) > 0.1) ||
(Mathf.Abs(Input.GetAxis("P1_VerticalAim")) > 0.1)) {
isTurning = true;
}
Update: confirmed that, yet again, Eric5h5 is right - this code does work, I tested it:
function Update () {
if (Input.GetAxis("Horizontal") ||
Input.GetAxis("Vertical")) {
isTurning = true;
}
}
The only question I would have, is if physical joysticks can generate spurious values, or whether Unity filters them out below a certain threshold.
Actually, the float from Input.GetAxis will implicitly evaluate as a boolean, where 0.0 == false and anything else == true. So artician's original code will work fine, once the relevant bits are put in parentheses properly.
A lot of weird things implicitly evaluate to booleans in javascript. http://stackoverflow.com/questions/1995113/strangest-language-feature/1998224#1998224
@Tetrad: Javascript isn't Unityscript, however, so most of that table is either a syntax error or doesn't evaluate the same in Unity.
UnityScript is based on .NET/$$anonymous$$ono, and .NET does NOT implicitly convert other types to bool. So things like 0, "", and null are NOT bools. You need to explicitly check for these using logical binary operators.