Node losing name

Godot Version

4.5

Question

In my world scene, I have 2 named nodes called the EnemyGenerator and EnvironmentGenerator.

During the game, the player can pause the game and navigate to e.g., a settings screen.
When navigating back, both generators lose their name and become respectively Node2D@23 and Node2D@24. In my code however, I rely on $EnemyGenerator and $EnvironmentGenerator. Is there a way around this?

I already tried looping over the children in the tree and if they are of type EnemyGenerator or EnvironmentGenerator, casting them as these nodes and setting their names, but that didn’t do the trick.

func _ensure_generator_names() -> void:
	for child in get_children():
		if child is EnemyGenerator:
			child.name = "EnemyGenerator"
		elif child is EnvironmentGenerator:
			child.name = "EnvironmentGenerator"

This is how I access them now, but the solution I mentioned where I can directly reference them would be way cleaner:

func apply_bomb_power_up():
	for enemy in enemies.get_children():
		(enemy as Enemy).destroy()

	for environment in environments.get_children():
		(environment as Environments).destroy()

	var enemy_generator: EnemyGenerator = null
	var environment_generator: EnvironmentGenerator = null

	for child in get_children():
		if child is EnemyGenerator:
			enemy_generator = child as EnemyGenerator
		elif child is EnvironmentGenerator:
			environment_generator = child as EnvironmentGenerator

	if enemy_generator:
		enemy_generator.pause_timers(2.5)
	else:
		printerr("Warning: EnemyGenerator not found")

	if environment_generator:
		environment_generator.pause_timers(2.5)
	else:
		printerr("Warning: EnvironmentGenerator not found")

add_child will often strip names, it’s second argument “force_readable_name” may help. Are you instantiating or re-adding these generator nodes to the scene?

Hold references to nodes instead of relying on names.
This name mangling will happen if you add a named node to the scene tree and there is already a sibling there with the same name. If you supply force_readable_name flag to add_child() call the duplicate name will be the node’s name plus numerical suffix. The same will happen if you assign the duplicate name to the node that’s already in the tree.

To repeat, if you add nodes dynamically - it’s much safer to keep references to them than accessing them by names. It’s also faster.

1 Like

Well, since I am using get_tree().change_scene_to_file(path) to navigate, I am instantiating new nodes if I understand correctly?

How can I hold references to nodes in code?

Put a reference into a persistent variable. child in your code is a node reference. Also the thing returned by PackedScene::instantiate() is a node reference.