Search code examples
godotgdscript

How to get a node in another scene godot?


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.


Solution

  • 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.