Why can't I get data from array?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Weexer

I am trying to make simple pathfinding system for my game, but I can’t find any way to get first point from array containing path to player, here is my code:

var way = []
var current_direction = Vector2(position)

func _physics_process(delta):
    way = Navigation2DServer.map_get_path($"../Navigation2D".get_rid(), $".".position, $"../Player".position, 0)
    current_direction = way[0]
    look_at(current_direction)

When starting level, game crashes returning this error:

Invalid get index '0' (on base: 'PoolVector2Array').

Maybe this is dumb question, but I hope someone will find me solution.

I assume you can’t get data from the array because it’s empty - which is probably the real problem.

What happens if you add an array size check, like this:

func _physics_process(delta):
    way = Navigation2DServer.map_get_path($"../Navigation2D".get_rid(), $".".position, $"../Player".position, 0)
    if way.size() > 0:
        current_direction = way[0]
        look_at(current_direction)

That’ll (obviously) prevent the access error you’re seeing. Maybe something just needs an extra frame to settle down - not sure.

jgodfrey | 2022-12-15 17:28

Ur smart dude, it works, thanks :slight_smile:

Weexer | 2022-12-15 19:23

:bust_in_silhouette: Reply From: jgodfrey

Based on the above discussion, the fix here was to wait for the map_get_path() call to return valid data (via an array size check) before attempting to access it.

func _physics_process(delta):
    way = Navigation2DServer.map_get_path($"../Navigation2D".get_rid(), $".".position, $"../Player".position, 0)
    if way.size() > 0:
        current_direction = way[0]
        look_at(current_direction)