Invalid Expression Term 'Else'
For some reason or another the second 'else' in this void is throwing out an exception. None of the normal things that would cause this seem to be present (no semicolons on the end of an if statement for example) so I am unsure what the problem could be. I have tried restructuring the void a bit, but nothing seems to alleviate the issue. Any help would be deeply appreciated.
void stateInAir(){
HandleHorizontalInput();
if (canJump) {
CanDoubleJump = true;
if (inputHoldTime < maxJumpButtonHoldTime && Input.GetKey (KeyCode.Space)) {
inputHoldTime += Time.deltaTime;
GetComponent<Rigidbody2D> ().velocity += new Vector2 (0, thePlayer.JumpAccel ());
} else {
if (Input.GetKeyDown (KeyCode.Space) && CanDoubleJump == true) {
setState (PlayerStates.ENTER_JUMP);
CanDoubleJump = false;
canJump = false;
}
}
else {
checkForGround ();
if (onGround) {
HandleLandOnGround ();
}
}
}
}
Answer by ZefanS · Mar 14, 2016 at 05:23 AM
Based on your current bracketing the statement goes like this:
if (...)
{
//...
}
else
{
//...
}
else
{
//...
}
An if-else statement can't have more than one else statement so you either need to use an else if (...) or restructure your brackets correctly.
As a side note, what you are referring to as a void is in fact called a method. The word void in this case indicates that the method has no return value. Method names should be formatted LikeThis.
Hope this helps!
@ZefanS Understood. In that case, to be clear, what would be a more efficient way to structure my brackets? For the time being I will attempt to make due with an else if, but if there is a better long-term way to solve this issue i would love to know about it.
It's not so much a question of more efficient. It's illogical to have two else statements. That's why you can't. If I have a statement like:
if (a == 1)
{
Debug.Log("a is 1");
}
else
{
Debug.Log("a is not 1");
}
then the else catches all conditions in which a is not 1. In other words, having more than one else is redundant and will cause an error.
In this particular case, I'm not sure what to recommend because I don't know how your script is supposed to work. In any case I would recommend doing some reading on conditional statements to make sure you properly understand how to use them.
As a side note, you should post responses to answers as comments, not as new answers. See the User Guide
Ah, understood, I think I improved it. I see what you mean about the else statements, and have now restructured the method not to use two. Thank you for taking the time to help me.
Your answer
Follow this Question
Related Questions
why my Unity Couldn't decompress package? 0 Answers
Survival Shooter Error CS0120 1 Answer