#Getting the path to a "sibling" node

5 messages · Page 1 of 1 (latest)

woven flower
#

Hi, quick question, is this not the right way to get the path to a sibling node in a node tree structure? I am trying to make an enemy jump to the player's position. The player is located on /root/LevelElements/, so I figured the path to the player node was exactly that. However, when the jump function is triggered, I get an error.

"Invalid get index 'position' (on base: 'null instance')."

Which means the engine can't find the player node, and as such, it can't find the position of something that doesn't seem to exist.

I attached a screenshot of the code, with the Level node tree structure visible. I wonder if the error might be caused because the enemy is within a deeper "folder" compared to the player, being located on /root/LevelElements/FOE/ ?

Thank you very much!

sick niche
#

I don't think the player is located in /root/LevelElements since the current scene's root node (Bosque_3_1 based on the screenshot) should be in the node path too.

But I don't think you want to use the node path to get to the player. If you ever changed it's location in a level scene tree, you would just get an error and have to fix things.

The best way to handle this is to have the player save a reference to itself somewhere where all the enemies can get to that reference.

You can do this with an autoload. Create a script called globals.gd and add a variable to it called player. Then in the player's _enter_tree method, have it set the autoload's player property to itself.

For globals.gd
extends Node
var player

then in the player script:

func _enter_tree():
Globals.player = self

Then in the enemy scripts they can use Globals.player to get the player's position or anything else it needs from the player.

woven flower
#

I thought Bosque_3_1 was the root. Is that wrong?

Thank you for the suggestion. I have an autoload script already that handles a few global signals. Do you think I should make another one, or just use the same old?

#

Also, sorry if I am asking for much, but why assign self to Global.player in the _enter_tree(): function?

Edit: Please ignore this question, I just realized the function is declared in the player script, and as such, it makes sense to assign self to Global.player

sick niche
# woven flower I thought Bosque_3_1 was the root. Is that wrong? Thank you for the suggestion....

The current scene is placed under the root node. So, I think it's /root/<scene root>. But it doesn't matter. I still advise not using the node path.

I personally would favor using a different script/autoload. This one is for event/signals. I like to keep things organized and separate. But that is just a personal opinion of mine. You should do as you feel comfortable with. There is no right or wrong answer here.