How do i reference something that isn't in the scene?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Millard

I have an enemy scene, where I’m defining the enemies characteristics. I am instancing the enemy in the level scene. I’m trying to get the enemy to check the distance between itself and the player, and if it’s within range move to the player. I know how to do that, but am having a terrible time referencing the player, because he isn’t in the enemy scene. I tried making a variable (player) and using get_node("res://Player") but it always returns null. How do i make this work? thanks, =)

:bust_in_silhouette: Reply From: kidscancode

That is not how node paths work. get_node() takes the path in the scene tree, not the file path, which is what res:// refers to.

When the game is running, there are no different “scenes” - that was just how you organized your different objects. When you instance a scene, all of its nodes are created and you add them to the scene tree.

Finding the path from one node to another in the scene tree works exactly like file folders do in your operating system. get_node("A") gets a child of the current node called “A”. get_node("../B") goes up one level and gets a child of that node called “B” (ie a sibling node). get_node("/root/C") gets the node “C” that’s at the top of the tree.

You should know where in the tree you’ve added things, but when the game is running, you can also click the “Remote” option in the scene tree to see the live node structure.

This is a very common question and I’ve written up a more detailed explanation here:

thnx, what I ended up doing was adding a script to the root node of the level:

onready var player_reference = $Player

func _ready():
    $enemy.player = player_reference

not perfect but it works, (I honestly don’t know why I didn’t think of it before. Thanks for the help! =)

Millard | 2020-11-21 21:11