Changing the argument of change_scene multiple times in a script

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By eviking

For some reason it seems that the change scene method is jumping to the whatever argument was used furthest down in the script. It should be respecting the counter, but it seems to be ignoring it.

For example, on level one you have 2 doors appear - you pick the correct door, you go to level 2 (which is res://Scenes/Stage002_Hallway.tscn However at this point I am always directed to res://Scenes/Stage004_Hallway.tscn So it is skipping over level two and three)

I have tried using variables with preload and load and that is throwing all kinds of odd errors.

extends Area2D

var counter = 0

func _ready() -> void:
	pass

func _process(delta):
	var bodies = get_overlapping_bodies()
	for body in bodies:
		if "Player" in body.name:
				if counter == 0:
					if Input.is_action_just_pressed("ui_spacebar"):
						get_tree().change_scene("res://Scenes/Stage002_Hallway.tscn")
						counter += 1
				if counter == 1:
					if Input.is_action_just_pressed("ui_spacebar"):
						get_tree().change_scene("res://Scenes/Stage003_Hallway.tscn")
						counter += 1
				if counter == 2:
					if Input.is_action_just_pressed("ui_spacebar"):
						get_tree().change_scene("res://Scenes/Stage004_Hallway.tscn")
	pass

As always thank you for any help.

:bust_in_silhouette: Reply From: jgodfrey

Your problem is in the if logic…

Assuming you start with counter = 0, you’ll enter this block of code…

if counter == 0:

There, you change the scene, and increment counter to 1.

Now, you get to this code:

if counter == 1:

Which is now also true. So, you process that block of code and increment counter to 2.

Now, you get to this code:

if counter == 2:

Which is now also true, so you process that code…

So, you end up processing each block of code, even though you intend to only process one of them on any given frame…

You need to somehow guard against entering successive blocks in the same frame. One way of doing that is to change the logic into a block of if | elif | else statements. So…

if counter == 0:
    # do 0 stuff
elif counter == 1:
    # do 1 stuff
else:
    # do 2 stuff