BOTH if/elif statement codes executed together (with variable) :(

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By amberlimshin
func _on_Area2D_input_event(viewport, event, shape_idx):

    var body = false
    if event is InputEventMouseButton and event.button_index == BUTTON_LEFT:
       if body == true:
	
		   anim_player.play_backwards("animation_name")
		   body = false
		
       elif body == false:
		
		   anim_player.play("animation_name")
		   on_body = true

So I’m trying to make just ONE block of code run. What happens here is The elif statement would execute first, and then immediately after, the if statement code executes (probably because of the changed variable).

But I thought with if/elif, only ONE block of code runs.

I tried using RETURN but it still doesn’t work.

I keep running into this problem and I don’t know how to solve it. I’m so confused and would appreciate your help. Thanks a lot!

When something happens and you don’t know why, it’s an opportunity for debugging, I like to use print(), for example, print("This is if check 1 from node: ", Node.name), in one of the ifs, this will allow you to understand what is happenning and potentially how to fix it.

The_Black_Chess_King | 2021-05-15 15:17

:bust_in_silhouette: Reply From: timothybrentwood

Moments like these definitely make you question your sanity as a programmer - we’ve all been here haha. if/elif does indeed function how you think they do, the block executions are mutually exclusive. The giveaway that something else was amiss should’ve been when you used return and both blocks still executed because return always kicks you out of a function exactly at that statement.

if event is InputEventMouseButton and event.button_index == BUTTON_LEFT:
checks if a mouse button left event occurs, when you click you’ll get both the events where event.pressed == true and event.pressed == false. Simplifying your conditionals:

if not (event is InputEventMouseButton):
   pass 
elif not (event.button_index == BUTTON_LEFT):
   pass
elif event.pressed == false:
   pass
elif body == true:
   anim_player.play_backwards("animation_name")
   body = false
elif body == false:
   anim_player.play("animation_name")
   on_body = true

This style of deduction of conditionals helps avoid nested ifs, compound conditionals and generally makes your code much more readable once you get used to it. The bottom two conditions will only execute if the input event is a pressed down left mouse button.

thANKS man! I found the problem. I forgot or didn’t know that having the

event.pressed == true

was necessary. But it makes sense. Because button click is true perpetually even if I click it just once. I’m learning as i go.

Thank you!

amberlimshin | 2021-05-16 02:00