Invalid set index error after await

Godot Version

4.2.1

Question

The problematic code:

extends State
class_name idle_calm

#When in this state, NPC would wander around it's spawn point with low speed

@export var target: CharacterBody2D
var search_range : int = 200
var wander_timer : float

func enter():
	await target.navigator
	target.entitySpeedCurr = 30
	new_point()
	
func new_point():
	var move_direction : Vector2
	move_direction = target.spawn_point + Vector2(randf_range(-1, 1), randf_range(-1, 1)).normalized() * randf_range(30, search_range)
	target.navigator.target_position = move_direction
	wander_timer = 10

Within ‘target’ code:

@onready var navigator : NavigationAgent2D = $NavigationAgent2D

On line:
target.navigator.target_position = move_direction
It gives error:
Invalid set index 'target_position' (on base: 'Nil') with value of type 'Vector2'.

From what I understand, it is because this line runs before navigator is properly initialized. Shouldn’t await target.navigator have solved this issue?

If I try using await target.navigator.target_position instead, it says:
Invalid get index 'target_position' (on base: 'Nil').

How can I solve it?

if you call new_point() as soon as possible after this character got created, it will say non existent navigator due to it being a @onready variable.

dont think you use await like that

1 Like

Then how do I make this part of code wait until navigator is properly initialized?

try

await get_tree().physics_frame

instead of

await target.navigator
1 Like

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