0 votes


I have a structure set like this:

    - Map (main scene)
    -- Player (sub scene, instanced)
    -- TileMap

On my Map.gd, I've set an onready variable like this:

onready var tilemap = get_node("TileMap")

which works fine, obviously.

However, if in my player.gd I set this:

onready var tilemap = get_parent().tilemap

It doesn't work, and return null, while

onready var tilemap = get_parent().get_node("TileMap")

works fine.

Is this a bug, or just something I'm not understanding well?

in Engine by (86 points)

1 Answer

+5 votes

_ready() is called on children first. Or to be more specific, _ready() is called on a node once all of its children are ready.

onready var tilemap = get_parent().tilemap

This doesn't work because the parent's _ready() function hasn't run yet, so the value of tilemap hasn't been set.

Rather than use get_parent(), you should call down the tree. On your Map script, tell the player about the tilemap:

$Player.tilemap = $TileMap

It's generally good practice for parents to manage children, not the other way around. Imagine if you run your player scene separately for testing. If there's a get_parent() call in there, it will crash. Instead, this way the parent "tells" the player what it needs to know when it's part of the map.

by (21,529 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.