+2 votes

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 activeitemslot 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.

Godot version Latest Release
in Engine by (55 points)

1 Answer

0 votes
Best answer

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

https://docs.godotengine.org/en/stable/classes/class_dictionary.html

by (1,635 points)
selected by

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.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.