Godot Version
4.2.2
Question
Can @export be used to get another objects position?
If so how can I use it?
4.2.2
Can @export be used to get another objects position?
If so how can I use it?
Yes. What you would do is to @export
a Node2D
(or Node3D
, depending on what youâre working on) of the object youâre interesting in querying, and then get its global_position
Then, on the Godot Editor, youâd add your script and add a reference to the object you want to track.
You can set a variable to reference an object in the scene tree in code without @export and get its position, like:
func where_my_node_at():
var my_node= get_node("path to my_node")
print(my_node.global_position)
or even easier assuming the node is uniquely named by right-clicking the node in question, selecting âAccess as Unique Nameâ then:
func where_my_node_at():
print(%my_node.global_position)
all @export does is mark a variable as editable in the inspector, and by default making it available to all functions within the script (while the above can be limited to function scope), so it becomes:
@export var my_node: Node3D
func _ready():
# this works
print(my_node.global_position)
func where_my_node_at():
# so does this
print(my_node.global_position)
and then you have to select the node from the tree.
It does âfeelâ like there may be a detrimental effect to using @export to track nodes in this way, but I donât think there is anything explicitly wrong with it. It just kinda enables a more erratic scene tree if you so chose to not keep things hierarchically organised and just traverse down the tree to find nodes.