- Home /
Trouble getting if statement to work
I'm trying to enable disable some gameobjects with if statements and FindGameobjectWithTag.
Needless to say I'm not doing it wright :(
Here is my code
///Swirl01
public void SetSwirl (string mSwirl01) {
//Default
if (mSwirl01 == "1")
a = true;
b = false;
c = false;
if (mSwirl01 == "2")
a = false;
b = true;
c = false;
if (mSwirl01 == "3")
a = false;
b = false;
c = true;
GameObject.FindGameObjectWithTag("swirl01").renderer.enabled = a;
GameObject.FindGameObjectWithTag("swirl02").renderer.enabled = b;
GameObject.FindGameObjectWithTag("swirl03").renderer.enabled = c;
}
I get the error "name a,b,c doesn't exist in the current context".
Can someone here please shed some light on this ??
You can use "switch":
switch(mSwirl01)
{
case "1":
a = true;
b = false;
c = false
break;
case "2":
...
break;
...
}
Even better, you could just do:
a = mSwirl01 == "1";
b = mSwirl01 == "2";
c = mSwirl01 == "3";
And avoid any if
statements what-so-ever. Or for even less code:
for (int i = 1; i <= 3; i++) {
GameObject.FindGameObjectWithTag("swirl0" + i).renderer.enabled = mSwirl01 == i.ToString();
}
And if you want your code to be even better, don't use FindGameObjectWithTag
and don't call your variables mSwirl01
.
Answer by Benproductions1 · May 11, 2014 at 09:24 AM
In C#, as well as UnityScript, JavaScript, Java and basically every language that uses {}
for code blocks, there are two "different" kinds of if
statements:
The first one works like expected and uses {}
to detonate the block of code contained in the statement. Take the following as an example:
if (input == "lolies") {
Debug.Log("Input was lolies");
//count the amount of lolies
lolies += 1;
}
The second kind does not use {}
and is criticize by many as bad practice mainly because of the exact problem you are having. The special thing about this kind, is that it only works for one line. Any other lines are not considered part of the block. Take the same code as an example:
if (input == "lolies")
Debug.Log("Input was lolies");
//count the amount of inputs
inputs += 1;
The second kind is not only annoying to maintain, since adding code to the block is impossible without adding {}
, but it also makes problems like yours harder to debug and (IMO) looks ugly in general.
Just as an optimization (and to give you the compile errors you need to realize the problem), you should make your other 2 statements else if
statements, since they can never be true if any of the above are.
Answer by Kannonfodder · May 11, 2014 at 11:48 AM
BenProductions answer above istrue, but looking at your error message you also haven't declared a,b or c anywhere. You need to declare variables before you can assign values to them so either at the beginning of your function, or at the top of your document if you need to use them elsewhere you need the following :
bool a,b,c;