There are quite a lot of ways to do it, because it is open ended how you choose to organize your data. If your item IDs are unique, I would recommend the most efficient method, create a dictionary where the keys are the integer ID numbers.
You can't assign integer IDs as keys with the default syntax though, because like variable the names can't start with numbers. You can get around this by doing the assignment during some initialization step.
extends Node2D
var dict = {} # Intialize empty dictionary
func _ready():
# Setup dictionary with integer keys. Brackets create/assign allow any type.
dict[0] = { name = "thing1", power = 100 }
dict[1] = { name = "thing2", power = 200 }
Then you can check that the keys are indeed integers using typeof
and print statements.
# Verify key is integer.
for key in dict.keys():
print(typeof(key) == TYPE_INT) # true / true
From this point forward to know if the dictionary contains an item ID, just use has()
.
# Do IDs exist?
var id = 1
print(dict.has(id)) # true
id = 2
print(dict.has(id)) # false
Going with the method you have, it is less optimal, but you can create a function that scans through the sub-dictionaries for IDs, assuming that nested key exists. Here is an example function of it, but recode it as it suits your project.
func _ready():
var d = {
thing1 = { id = 0, power = 100 },
thing2 = { id = 1, power = 200 }
}
print(has_id(d, 2)) # false
func has_id(dict, item_id):
# Be sure sub dictionary values have a key called "id"
for entry in dict.values():
if(entry.id == item_id):
return true
return false
Lastly, the error you're getting is from comparing incompatible types. If one field is stored as an integer and somewhere else brought in as a string, you can type cast.
int(dict_id) == obj_id
or
dict_id == str(obj_id)