How to get a node in another scene godot?

Viewed 2375

I am making a game with multiple scenes and need to have varibles that are get_node(node from another scene) and I don't know how to get nodes from another scene.

2 Answers

If I understand correctly, you want to connect to signals from a node in another scene.


The direct approach would work:

const bullet := preload("res://Bullet.tscn")

func create_bullet() -> void:
    var instance := bullet.instance()
    instance.connect("hit", self, "method")
    get_parent().add_child(instance)
    # etc

func method() -> void:
    # whatever
    pass

However, this is not always convenient.


To decouple the code further, I suggest using a Signal Bus.

The insight is that object can emit signals of other objects. And thus, if you have a common object that everybody can refer to, you can put your signals there.

To have an object that everybody can refer to, create an autoload (singleton). You can call it SignalBus.

Have a script in autoload where you define signals. For example:

signal hit

Then where you need to emit the signal, do this:

SignalBus.emit_signal("hit")

And to connect to it where you need to receive it, do this:

func _ready() -> void:
    SignalBus.connect("hit", self, "method")

func method() -> void:
    # whatever
    pass

Since every scene can reference the autoload, any of them can emit and any of them can receive the signal. They don't need to know each other.

Expanding on the answer by @Theraot for those using Godot 4, wherever you need to receive the "hit" signal...

func _ready():
    initialize_signals()

func initialize_signals():
    SignalBus.connect("hit", self.call("method"))
Related