NavigationRegion2D not baking at runtime

Godot Version

4.5

Question

Hi, I have a game that randomly places trees around the game world. I also have enemies that need pathfinding, which is why I’ve decided that I need to bake the NavigationRegion2D at runtime right after the trees are placed. For some reason though, that just refuses to work. The strange part is that it bakes perfectly if I place the trees manually and bake the region through the editor.
Here is the code I am trying to run:

extends Node
@onready var tilemap : TileMapLayer = get_node("../Tilemap")
@onready var spawn_points_node : Node = get_node("../SpawnPoints")
@onready var player : Player = get_node("../Player")
var tree_scene = preload("res://Scenes/Objects/tree.tscn")
@onready var navigation_region_2d: NavigationRegion2D = $"../NavigationRegion2D"


var grass_tile_atlas_coords = Vector2i(0, 0)
var sand_tile_atlas_coords = Vector2i(1, 0)
var water_tile_atlas_coords = Vector2i(2, 0)

@export_range(0, 100, 1) var tree_spawn_change = 10

func _ready() -> void:
	generate_trees()
	navigation_region_2d.bake_navigation_polygon(true)
	choose_spawn_point()
	
func generate_trees():
	for x in range(Global.tilemap_size):
		for y in range(Global.tilemap_size):
			if tilemap.get_cell_atlas_coords(Vector2i(x, y)) == grass_tile_atlas_coords:
				var random = randi_range(0, 100)
				if random <= tree_spawn_change:
					var tree = tree_scene.instantiate()
					tree.global_position = Global.tilemap_coords_to_global_coords(Vector2(x, y))
					navigation_region_2d.add_child.call_deferred(tree)
					

func choose_spawn_point():
	var rand = randi_range(0, spawn_points_node.get_child_count())
	var i = 0
	for child in spawn_points_node.get_children():
		if i == rand:
			player.global_position = child.global_position
		else:
			child.queue_free()
		i += 1

And here is a video of me showing the problem:
https://youtu.be/0OxTXPPpSY0

Thanks, in advance!

You are deferring add child, so the trees are actually added on the frame after you call bake_navigation_polygon. You could try to defer the bake too, or remove call_deferred.

I think I found the issue. I just had a lot of trees an it took a long time till the polygon baked completely :sweat_smile: