|
|
|
|
Attention |
Topic was automatically imported from the old Question2Answer platform. |
|
Asked By |
Elis |
Hi,
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?
|
|
|
|
Reply From: |
kidscancode |
_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.