How do I get a reference to a node from another scene in my script

Godot Version

4.4.1

Question

How do I get a reference to a node in another scene, to use in my script? I need to reparent a scene to a container in another scene, but to do so I need a reference to that container, how do I get that? I was told to use @export but I can’t figure out how to exactly use it.

Easiest way it to add a new group on the Groups Tab under the Nodes Tab and then add your object to that.

Then reference it in your script like so:

@onready var player: Player = get_tree().get_first_node_in_group("Player")

if its in a group will it always be in the scene? Or can I still reference it even if it isn’t instanced?

You can only reference it if it has been created and is in the scene tree as far as I know. There are other options, that’s just the easiest.

In this scenario, its not particularly easy for me to have it in the scene tree. Would it be possible to instead make a reference to it that isn’t on ready? Maybe using @export or something?

Yes.

@export var my_object: PackedScene

Then you just drag the scene from the FileSystem into the variable in the inspector.

Then to reference it:

func do_something() -> void:
	var instance = my_object.instantiate()
2 Likes