Reputation: 15
My if
statement runs even if the condition is not true. Variable as already been change in the first loop but due to getkeydown event it keeps looping 4 times
Just to introduce i'm making this with C# in Unity and diferent from other process it runs by frames, so each frame it will run the code again. So basically I'm verifying if the user as pass a situation, if not, the code will enter in the if statement and give a new value to the array index (situacao[8]) my problem is due to GetKeyDown it will run 4 times until the frame is updated (or so i read in another post). It should be simple, since i change the value to 1 it should not enter in the if again.
if (Input.GetKeyDown(KeyCode.Space))
{
meuEstado = estado.Cela;
}
else if (Input.GetKeyDown(KeyCode.G))
{
print(situacao[8]);
texto.text = "He look for the Window.";
if (situacao[8] != 1)
{
texto.text += "\nand notice there is a bird there!";
situacao[8] = 1;
}
}
The print output is 0 - 1 - 1 - 1
but it should just give a 0
. It's not showing any console errors.
PROBLEM DISCOVER:
I had 4 textboxes associated to the same script all of them were also variable assigned.
SOLUTION:
Just add a script to one object and associate the other objects there
Upvotes: 0
Views: 412
Reputation: 20269
You're printing before you check if the value is 1, so it will always print the current value of situacao[8]
, which is 0 the first time, then 1 for every time after that.
If you only want it to print when situacao[8]
is not 1, consider moving it inside the if statement like so:
else if (Input.GetKeyDown(KeyCode.G))
{
texto.text = "He look for the Window.";
if (situacao[8] != 1)
{
print(situacao[8]);
texto.text += "\nand notice there is a bird there!";
situacao[8] = 1;
}
}
Including this script on exactly one gameobject instead of 4 will result in only "0" being printed for the first press, and for no further presses.
Upvotes: 3