Finding a resource in an array by matching its ID to a resource of the same type

Godot Version

4.3

Question

I’m working on a level data system that creates a set of data tracking level variables when it’s first beaten against subsequent attempts to check for improvements. Each of these LevelData resources has an int LevelID. I’m struggling to find a way for a comparison function to take the incoming LevelData, then find the existing LevelData with the same LevelID inside of the array containing all level data. find() isn’t proving too helpful, maybe I’m using it wrong.

since your level data resources aren’t saved in any data structure that sorts them in any way by LevelID there is no particular algorithm that would make the search for a certain resource more efficient. Therefore looping through all elements of your level data array and checking for the LevelID should be fine.

var level_data : Array[YourLevelDataResource]


# returns the first level data resource with matching id
func find_level_data_or_null(level_id : int) ->YourLevelDataResource :
   for data in level_data:
      if data.LeveID == level_id:
         return data

   return null
# returns the index of the first level data resource with matching id (-1 if no match)
func get_level_data_index(level_id : int) -> int:
   for i in level_data.size():
      if level_data[i].LeveID == level_id:
         return i

   return -1
1 Like

I ended up having the game go through them by their index within the dataset, they’ll always be added in the same order so they always generate in a predictable manner. That code is certainly worth bearing in mind though, thanks.

1 Like