How do I use @export?

Godot Version

4.2.2

Question

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.

2 Likes

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.

2 Likes