I have this setup:

Main
|-- Collider
|-- Model

Now, in Main I want to do something like this:

@onready var collider: CollisionShape3D = get_node("/root/Collider")

func _ready():
    print(collider)

But I get an error because collider is null.

To circumvent this I'm declaring "collider" as an @export var and manually assigning it in the editor, but is there a way to this just with code, maybe using signals? I tried with the ready() and enter_tree() signals of Collider but it still failed.

  • xyz and Toxe replied to this.
  • correojon Well if you want to get the parent, just go one level up in the hierarchy "..", or get_parent(). No need to go up all the way to Main.

    correojon Main is not root. Your absolute path to Collider is likely incorrect. In this case it'd be better to use relative path. Check the remote scene tree to see the actual scene tree hierarchy at runtime.

    correojon Do it like this:

    @onready var collider1: CollisionShape3D = $Collider
    @onready var collider2: CollisionShape3D = get_node("Collider")

    People usually prefer the first version.

    Thanks guys, that worked fine 🙂

    Another related question: If I now have to get a reference to Main from a script running on Model...how would I do that? Note that is a scene of an enemy, which then gets put into a Level scene several times:

    Main
    |-Enemy
    |-Enemy2
    |-Enemy3

    And inside each Enemy I have:

    Enemy
    |- Model
    |- Collider

    When I tried to get a reference from model to enemy like this:

    @onready var enemy: CharacterBody3D = get_node("../../Enemy")

    It works on the enemy scene, but when I run the level scene, all enemies are getting the reference to "Enemy" instead of Enemy2 getting a reference to "Enemy2" and Enemy3 getting one to "Enemy3".

    • xyz replied to this.

      correojon Well if you want to get the parent, just go one level up in the hierarchy "..", or get_parent(). No need to go up all the way to Main.