How to get a variable from a child node?

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

Consider the following project structure:

game
–world
----someobjects
----player

-world is a child of game
-player and someobjects are both children of world.

if i want to store (for example) the player’s x position in the world node, how do i do this?

i tried:

player_pos = get_node("world/player").position

but it throws an error: Node not found: world/player

if there is any other way to reference player.position im open to suggestions

thanks!

edit: i actually got it to work by doing this in world’s script:

onready var playernode = get_node("player")


func _process(delta):
	print(playernode.position.x)

it wants you to make a variable first containing the node. before i was directly calling get node(player).position

I’m not sure how to do this either and I had to on a recent project, but I found a workaround where I used a signal to broadcast the position of the subject (world/player in your case) and the other node received it and stored it in a local variable.

my script for the subject (Army):

signal ArmyPosition(armyPosition)

func _physics_process(delta):
   emit_signal("ArmyPosition", position)
   pass

my script for the other one (this one’s the MovementLine):

func get_ArmyPosition(newPosition):
  AverageArmyPosition = newPosition

pass

and then I had the world connect the two:

onready var Army = preload("res://Army.tscn")
func _ready():
  var army = Army.instance()
   add_child(army)
  army.connect("destination_changed", $MovementLine, "_on_destination_changed")
  army.connect("ArmyPosition", $MovementLine, "get_ArmyPosition")
pass

I know this is clunky and probably performance intensive, but it worked for me :slight_smile:

I hope this helps!

P.S. I’m new to the forums, so sorry if the tabs are weird but I couldn’t figure out how to indent properly in the code block

Agentfox | 2019-04-13 15:52

:bust_in_silhouette: Reply From: Pinandu

try

player_posx = get_node("/root/game/world/player").position.x
:bust_in_silhouette: Reply From: brainbug

the path is allways relative to the current node

Node
----Child
--------------Grand_child

from Node:

get_node("Child")

or

$Child

get_node("Child/Grand_child")
$Child/Grand_child