- Home /
EXTREMELY basic scripting question.
I feel stupid.
What's wrong with this code:
function Start () {
if ((whichTeam != 1) || (whichTeam != 2)) {
Debug.Log ("Invalid team value");
}
}
It doesn't work, just writes Invalid team value to the log every time I hit play, no matter what the value of whichTeam is. I am confused. Seems to work if I change the !=
's to ==
's, and also works if I just put (whichTeam != 1)
Easy to work around, but I just want to know, what's wrong with this? Or is Unity incapable of handling that?
Answer by simplyRubbish · Feb 18, 2011 at 04:11 AM
What are the possible values which team can be? If it's 1 or 2 then it will always go into there because the OR operator. If which team is equal to 1 the second condition will let it pass as true and vice versa.
Duh. Now I feel really stupid. I guess I need to use &&.
I am new to scripting, and I was thinking in terms of how I would describe it to someone using language, not using math. I need to get used to thinking of scripting more as math, despite it's basis in language. (obviously).
Thanks for taking the time to set me straight.
No worries, we've all been there and I myself and many others have made that exact mistake. Live and learn I always say.
Answer by tertle · Feb 18, 2011 at 04:14 AM
Your code makes no sense, it'll enter the if statement for whatever value of whichTeam.
if whichTeam is equal to 1 then whichTeam != 2 therefore enters if statement
if whichTeam is equal to 2 then whichTeam != 1 therefore enters if statement
if whichTeam is equal to another value then whichTeam != 1 && whichTeam != 2 (both statements true) therefore enters if statement
Every case enters if statement.
If you want it to only enter the statement when whichteam doesn't equal 1 or 2, then you want.
(whichTeam != 1) && (whichTeam != 2)
or
!((whichTeam == 1) || (whichTeam == 2))
should be able to mark two answers as correct, you wrote in when I was typing my response to the other...