Attempt to call function 'find_child' in base 'null instance' on a null instance

Godot Version

Godot 4

Question

Hello, why am I getting ‘null instance’ error in following script? My scene includes main 2d Node and its children Player( CharacterBody2d) and Terrain (Tilemap)

extends CharacterBody2D

var dir = Vector2.ZERO
var cell_size

@onready var world = get_tree().get_root().find_parent(“World”)
@onready var tilemap = world.find_child(“Terrain”)

func _ready():
cell_size = tilemap.tile_set.tile_size

I tried to change order of Player and Terrain in the scene but that didnt help.

get_tree().get_root() returns the root node.
You attempt to find a parent of the root node which has as name “World”.
Since it is the root node, it doesn’t have any parents by definition so the find_parent function returns null.

Of so I modified it in this way:

@onready var world = get_parent()
@onready var tilemap = world.find_child(“Terrain”)

Now it seems like it works.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.