Player node isn't reparenting

Godot Version

v4.4.1

Question

For some reason, my player node isn’t reparenting to the player holder.

Important Function of Player Script

`
func _ready() → void:

health = Vars.playerStats.health
books = Vars.playerStats.books
uses = Vars.playerStats.uses
for i in 9:
	get_node("Menu/Bookshelf/HBoxContainer/%s/AnimatedSprite2D" % i).animation = Books.book.find_key(books[i])
	uses[i] = Books.bookList[Books.book.find_key(books[i])].uses
	get_node("Menu/Bookshelf/HBoxContainer/%s/Uses" % i).text = str(uses[i])
held_books_update()
if Vars.floor == 0:
	print("floor 0")
	reparent.call_deferred(get_parent().get_parent().get_parent().get_node("PlayerHolder"))
	floor_books()
elif Vars.floor == 1:  ##  Activated Case
	print(get_parent().get_parent().get_parent().get_node("PlayerHolder"))  ##  Confirmed that the PlayerHolder exists in the exact path before reparenting
	reparent(get_parent().get_parent().get_parent().get_node("PlayerHolder"))
	Vars.game = true
	unpause()
	get_parent().get_parent().spawn_guys()  ##  Invalid call. Nonexistent function 'spawn_guys' in base Node2D
else:
	print("floor ", Vars.floor)
	pow(Vars.modifier, 1.05)
	reparent.call_deferred(get_parent().get_parent().get_parent().get_node("PlayerHolder"))
	Vars.game = true
	unpause()
	get_parent().get_parent().spawn_guys()`

spawn_guys function

(attached to Game node)
`
func spawn_guys():

for i in $Rooms.get_children():
	i.spawn_guys()`

Remote Scene Tree

Local Scene Tree for Game

Local Scene Tree for Start

To post multiline GDScript code, please put it between ticks like this:
```gd
# code
```
The “gd” behind the first set of ticks helps with syntax highlighting.

It’s considered unsafe for children to have direct references to their parents or call functions on them, so doing something like get_parent().get_parent() isn’t recommended.

Instead, you can follow the principle “signal up, function down”, i.e. have children emit signals to which you connect functions of their parents.
For example:

# a snipped from your code, more or less how it could look with signals
elif Vars.floor == 1:
	reparent_to_player_holder.emit() # define reparent_player as a signal
	Vars.game = true
	unpause()
	spawn_guys.emit() # define spawn_guys as a signal

Now you can connect reparent_to_player_holder and spawn_guys to corresponding functions in a parent, for example the node that you could (but shouldn’t) get with get_parent().get_parent().get_parent()

1 Like

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