Errors returning for collision when I try to change scene

Godot Version

Godot 4.5.0

Question

I’m trying to make a 2D RPG and I want the scene to be changed once an enemy in the main world collides with the player. I have the code and the collision works doing anything else, but when I try to change the scene specifically it gives two errors. Parameter “data.tree” is null and cannot call method ‘change_scene_to_file’ on a null value. My code always works otherwise though, and when I try to change the scene using something like a button or after the enemy collides with a pathfinding wall, it works perfectly fine.

#the code that the errors say is wrong 
func _physics_process(_delta: float) -> void:
	_move_towards_player()

func _move_towards_player() -> void:
	set_movement_target(player.position)


#the code that isn't working
move_and_slide()
for i in get_slide_collision_count():
    get_slide_collision(i)
	get_tree().change_scene_to_file("res://battle_mode___arena.tscn")

What needs to be changed or fixed?

Changing scenes has a quirk that invalidates get_tree(), after the first change scene call the tree will be null. You must avoid calling change scene twice in a frame, which your for i in get_slide_collision_count(): may trigger more than once per frame as there often are more than one slide collisions.

Your code seems odd as it doesn’t check for anything other than a slide collision, so you could rewrite it without the for loop. But if this is only for an example I’d recommend using the keyword break to stop a loop from continuing

move_and_slide()
for i in get_slide_collision_count():
    get_slide_collision(i)
	get_tree().change_scene_to_file("res://battle_mode___arena.tscn")
    break # stops for loop

It would make more sense with a check

move_and_slide()
for i in get_slide_collision_count():
    var collider = get_slide_collision(i).get_collider()
    if collider.name == "Player":
	    get_tree().change_scene_to_file("res://battle_mode___arena.tscn")
        break # stops for loop only if colliding with "Player"
1 Like

It no longer crashes, but the program freezes instead and returns this error.

_move_towards_player: Invalid access to property or key ‘name’ on a base object of type ‘KinematicCollision2D’.
enemy.gd:50 @ _move_towards_player()
enemy.gd:50 @ _move_towards_player()
enemy.gd:21 @ _physics_process()

Ah my sample only got the collision data, I’ll edit it to include .get_collider(). It is only a example though, your node may be named something else, especially if it’s based on an enemy entering the area, you may have to use something other than the node name, like a class_name with is or a group with .is_in_group

1 Like