Getting the index from a dictionary.

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

In my inventory system, I need to be able to use the selected item in the hotbar. This is the script I use to get the hotbar’s current item.

print(PlayerInventory.hotbar[PlayerInventory.active_item_slot])

This normally works but whenever there is not an index for the active_item_slot I use, It crashes. For example, It crashes whenever the only item in the inventory is in the first slot but the active slot is the second. I only need it to run whenever the index actually exists.

:bust_in_silhouette: Reply From: Gluon

You can use if and in to check if something is in a dictionary. For example

if "godot" in {"godot": "engine"}:

so you can use a line like this to check if it actually exists before you run the code which crashes if it doesnt exist.

FYI you can also check the godot documentation here

Thank you! I had actually solved it a couple minutes ago by basically using the same line of code you did. I just used the .has function instead.

Mr. Gamezz | 2022-01-10 01:45