1

Instead of maintaining 2 separate variables for my exported node path, like this:

extends Node2D

export(NodePath) var target_path
var target_node

func _ready():
    target_node=get_node(target_path)

is there any way to export only 1 variable and directly get the node?

3 Answers 3

3

Godot 4 with GDScript 2 offers an even more concise way to export only one variable and directly get a node.

@export var target_node: Node

This also offers the advantage of setting constraints on the type of the node, where Node could be replaced by Node2D, Control, or even a node with a script attached that you've defined using class_name.

@export var camera: Camera2D
@export var fancy_camera: MyCamera2D
Sign up to request clarification or add additional context in comments.

Comments

0

There is, and it's a one liner:

extends Node2D
export (NodePath) onready var target_node=get_node(target_node)

Turns out someone did it 2 years ago.

Comments

0

With Godot4 Script the one-liner doesn't work anymore, as you'd write:

@export_node_path @onready var target_node=get_node(target_node)

which produces these errors:

Could not resolve member "target_node": Cyclic reference.
"@export_node_path" annotation requires a variable of type "NodePath" but type "Node" was given instead.
The "@onready" annotation will make the default value to be set after the "@export" takes effect and will override it. (Warning treated as error.)

So you'll have to write 2 lines:

@export_node_path var target_node
@onready var _target_node = get_node(target_node)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.