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?

asked May 14, 2019 in Engine by Elis (87 points)

1 Answer

+2 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.

answered May 14, 2019 by kidscancode (17,704 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 How to use this Q&A? before posting your first questions.