0 votes

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, =)

in Engine by (370 points)

1 Answer

+3 votes

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:
http://kidscancode.org/godot_recipes/basics/getting_nodes/

by (20,477 points)

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! =)

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.