SceneTree.change_scene_to() restarts the scene instead

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

Backstory: I’ve made a scene named Level as a template for all of the levels of my game and used “New inherited scene” feature to inherit the levels and edit the stuff I need to. To tell the level which scene is next, I used export variable in the main level script and manually selected the scenes which are next (So I won’t have to create an inherited script too just for that).

Code:

extends Node2D
export var next_level : PackedScene
onready var player = get_node("Actors/Player")

func _ready():
	$LevelEnder.connect("body_entered", self, "end_level")

func end_level(body):
	if body == player:
		if next_level:
			get_tree().change_scene_to(next_level)
		else:
			print_debug("No next level defined!")
	
func restart_level():
	get_tree().reload_current_scene()

The actual problem: There you see I’m using get_tree().change_scene_to(next_level) in the function end_level but it restarts the scene instead. I’ve double checked If I’ve selected the wrong level but I haven’t.

:bust_in_silhouette: Reply From: IceExplosive

The code looks ok as is… there really has to be a problem with setup instead of code.

First put break point into end_level method and check what is inside next_level variable.
If you start scene A, there must be a different scene B stored.

You can check names for example by:

var current = self.name;
var next = next_level.instance().name;

Second, could possibly scene B hit a condition, under which it would return back to scene A making it restart like behaviour?

:bust_in_silhouette: Reply From: spoicat

I figured it out. In my game, if player leaves a certain area, player has to die. And when I change the scene, the “area_exited” signal is executed from that Area2D and it restarts the scene before it can change to next level.

So I simply added this to level script:

 var finished : bool = false 

And this to the Area2Ds script:

func _on_body_exited(body):
	if body == level.player and !level.finished:
		level.restart_level()

Anyway still thanks to IceExplosive for trying to help!