How do I work around "Node needs a parent to be reparented." error?

Godot Version

4.2

Question

Hi, I’m trying to switch levels when the player walks into an Area2D. I want to move the old player and camera from one level scene into the new level scene, but the screen shows nothing but gray on transition and I receive an error.

extends Area2D

@export var next_level : PackedScene
@export var player_path : NodePath
@export var camera_path : NodePath

func _ready():
	self.body_entered.connect(_on_body_entered)

func _on_body_entered(body):
	if body is CharacterBody2D:
		var root = get_tree().get_root()
		var old_scene =  root.get_child(0)
		var next_scene = next_level.instantiate()
		var player_instance = get_node_or_null(player_path)
		var camera_instance = get_node_or_null(camera_path)

		if player_instance != null:
			player_instance.reparent(next_scene)

		if camera_instance != null:
			camera_instance.reparent(next_scene)
			
		old_scene.queue_free()
		next_scene.reparent(root)



Error:

E 0:00:04:0341   Door.gd:25 @ _on_body_entered(): Node needs a parent to be reparented.
  <C++ Error>    Parameter "data.parent" is null.
  <C++ Source>   scene/main/node.cpp:1720 @ reparent()
  <Stack Trace>  Door.gd:25 @ _on_body_entered()

will need to add child this “next scene” first then it became a node in the scene tree, and be able to do reparent to it

1 Like

It worked

I changed

		next_scene.reparent(root)

to

		root.add_child(next_scene)

My player and camera didn’t transfer into the new scene, but I suppose that’s an issue for another topic.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.