'Invalid get index '0' (on base: 'Array')' due to rand_range variable dropping to 0

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

Hi folks,

I’m using a set of 8 spawn points for targets to appear at, with the spawn location randomized from a group ‘active_spawn’ (spawn points with no target) and a rand_range which uses the size of the ‘active_spawn’ group as it’s higher limit.

var possible_spawns = get_tree().get_nodes_in_group("active_spawn")
var spawn_range = get_tree().get_nodes_in_group("active_spawn").size()
var random_spawn = possible_spawns[rand_range(0, spawn_range)]

My issue is that once all 8 spawn points are occupied and the group ‘active_spawn’ is empty, any further atempts to spawn a target result in the error ‘Invalid get index ‘0’ (on base: ‘Array’)’ which crashes the game.

Any attempts of mine to add exception handling have had no effect. I’m rather stuck, so would appreciate any insight you’re able to provide! If I haven’t provided enough information/code, please let me know.

Cheers,
Matt

:bust_in_silhouette: Reply From: exuin

GDScript does not have exception handling. Just put an if statement that only spawns an enemy if there is at least one node in the group “active_spawn”.

This worked perfectly, thank you! I got so focused on sorting it within the array itself that I was a bit blinded to other ways of solving this.

Matto225 | 2021-04-26 17:49