Node dynamically added to the scene by code cannot be accessed through '%' to retrieve another node already loaded in the scene

Godot Version



here I created an node named “mob” with a bounded script. and this script will initialize a node named player witch is pined “unique name” and the node of player already loaded in scene.
when the game run , the root node named “game” will create the node of “mob” throw script. but the script of “mob” bounded can not get the node of player when the game run, the player is null in the script. that was confuses me

The script of “mob” bounded is as follows:

extends CharacterBody2D
@onready var player: CharacterBody2D = %player
func _physics_process(delta: float) → void:
var direction = global_position.direction_to(player.global_position)

and the node struct of scene as follow:
CharacterBody2D: player
CharacterBody2D: mob (Create dynamically from script)

the node of game will create the node of mob and invoke func “addchlid(mob)” in game node.

it doesnt work because, the mob scene doesnt have node with unique name of player inside it
this will work if you try :

@onready var player: CharacterBody2D = $"../player"

another way to make the mob scene knows or have the player reference is to actually send the player scene node when creating the mob scene

So before you add_child(mob), you of course will need to instantiate() it from PackedScene
from there when you instantiate the PackedScene like this
in game node2d script:

@onready var player_node=$player

var mob= mob_scene.instantiate()

this way also let your mob knows or have reference to the player

i know some users also make use of group to group the enemy and the player
you can get the player also by getting group nodes of player, but this require you to set and add player to the group

got it!
so,it‘s means that the “unique name ” title just work on the current scene if I load the “player” from “%player”. it can’t be instantiate from another scene throw this way I think .

1 Like