get_node() -- Access variables

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

My tree:

Hi. I want to access sibling node(player – sword)
player script:

var health=100

sword script:

onready var variable1=get_node(“/root/world/player”)
func _ready():

i am getting a mistake== Node not found: /root/world/player.

Please help. Thanks

:bust_in_silhouette: Reply From: ejricketts

A better way to access the node would be by executing:

onready var player = $Player

such that you can call:

player_health =

Doing it this way is more standard and can give you access to any of the children of the script holding node.

Sorry, but not work. This time I am getting a new error. == Invalid get index “health” (on base: “Nil”)

New sword script:
onready var player=$player

func _ready():

tncft4 | 2021-01-16 14:08

After the ‘$’ sign, the word need the be the name of the node you want to reference, is the node called ‘player’ exactly like that? (No capitals etc)

ejricketts | 2021-01-16 14:29

Yes , it is. .

tncft4 | 2021-01-16 14:34

Do you want a screenshot?

tncft4 | 2021-01-16 14:52

So it looks as though the sword and the player are not a child of each-other. You’ll need to access the tree as a whole and then your player

Try using get_tree() and then attaining a child in the tree

A screenshot would be helpful

ejricketts | 2021-01-16 14:53

Yes. THe Sword and the player not a child of each-other. How can I do what you’re saying

tncft4 | 2021-01-16 14:59

Make the sword a child of the player and try the original plan, the sword is a part of the player I assume so really it should be a child of it

ejricketts | 2021-01-16 15:21

main scene == WORLD (Node 2d)
WORLD’s childs == player , sword
player’s childs== Sprite , CollisionBox2d
sword’s childs== Sprite, CollisionBOx2d

The player and the sword are child of world.
if i can “Make the sword a child of the player” This time sword and player move the together.

tncft4 | 2021-01-16 15:36

Do they need to be separate?

ejricketts | 2021-01-16 15:50

Unfortunately yes

tncft4 | 2021-01-16 15:52

Can you put your code on google drive (or other so I can have a look please)?


ejricketts | 2021-01-16 17:37

I have got it working! :slight_smile:

So in your sword script you want something like this…

onready var player = get_parent().get_node("player")

func _ready():

and then clearly in you player script you need var health = 100 somewhere.

Let me know if this works!

ejricketts | 2021-01-16 17:50

WOOOOOWWWW! You are awesome. It’s work. Thanks for everything.

tncft4 | 2021-01-16 18:14

No problem!

What might be good to read for the future when accessing other nodes is this page:

Learning about signals will really open up your options

ejricketts | 2021-01-16 23:04