Why doesn't this code work?

function Weapon()
{
if (Input.GetKeyDown(“t”) && low == true)
{
low = false;
mid = true;
high = false;
}
if (Input.GetKeyDown(“t”) && mid == true)
{
low = false;
mid = false;
high = true;
}
if (Input.GetKeyDown(“t”) && high == true)
{
low = true;
mid = false;
high = false;
}
}
YET FOR SOME REASON THIS CODE WORKS FINE
function Weapon()
{
if (Input.GetKeyDown(“t”) && low == true)
{
low = false;
mid = true;
high = false;
}
else if (Input.GetKeyDown(“t”) && mid == true)
{
low = false;
mid = false;
high = true;
}
else if (Input.GetKeyDown(“t”) && high == true)
{
low = true;
mid = false;
high = false;
}
}

I have read many times that if else is a stupid statement that should never be used but it worked for me.

In the first code sample, since you don’t have else in between each if, each of those statements is always true - it basically goes through and toggles through all the values every time you hit t.

With the else clauses in the second sample, only the first one of the ifs that evaluates as true is executed.

Running through the first example…

  • if the key is hit and low is true, low gets set to false and mid is set to true.
  • when the next if is evaluated, the key is still down, and mid is true, so it sets mid to false and high to true.
  • when the final if is evaluated, the key is still down and high is true, so it sets low to true and high to false.

The next time you hit the key it will repeat the same steps.

In the second sample, the else makes sure only the very first if that’s true will be executed, and none of the others.