Search code examples
godotgdscript

Why is Godot having problems with elif statements?


Here is the code with the elif statement, this one and elif statements in general. I'm fairly new to Godot and this is me following an example and learning along:

extends AnimatedSprite

func _process(delta):
    
     if Input.is_action_pressed("ui_right"):
      play("Run")
     flip_h = false
     elif  Input.is_action_pressed("ui_left"):
         play("Run")
        flip_h = true
        else:
            play("Idle")
     pass

And I get this error:

error(7,3):Error parsing expression, misplaced: elif

So what could it be? I have no idea how to solve this issue.


Solution

  • It has to do with how you are indenting your code. Here's a quick look at the documentation.

    if, elif and else should all be on the same level of indentation. Everything inside the statements should be indented one additional level. Your code would look like this:

    extends AnimatedSprite
    
    func _process(delta): 
      if Input.is_action_pressed("ui_right"):
        play("Run")
        flip_h = false
      elif Input.is_action_pressed("ui_left"):
        play("Run")
        flip_h = true
      else:
        play("Idle")
    

    Also, pass isn't needed at the end because you're calling play("Idle") instead.