Using enums to expand item data types?

Godot Version

4.2.1 stable mono

Question

I am setting up an inventory system and inside my itemData script I want to have different variables depending on the item type. I have the base variables i want for all the item types but I do not know how to add specific variables to the certain types inside my enum. Im not sure if this is the best way to organize item data, should i use multiple scripts to manage different item types or can i do it all in one.

class_name ItemData
extends Resource

#These are the base item types and variables for all items
enum itemType {RESOURCE, CONSUMABLE, EQUIPMENT, WEAPON}
@export var type: itemType
@export var itemName: String
@export var stackable: bool
@export var stackCount: int
@export var itemValue: int
@export var itemIcon: Texture2D
@export_multiline var description: String

#Check item type
func set_item_data_from_itemType():
#Here I wanted to add more variables based off the type chosen from above
	match itemType:
		itemType.RESOURCE:
			return
		
		itemType.CONSUMABLE:
			enum consumableType {FOOD, DRINK, POTION}
			@export var type: consumableType
			@export var healAmount: int
			
		itemType.EQUIPMENT:
			@export var itemArmor: int
			
		itemType.WEAPON:
			@export var itemDamage: int

``

This is what i though i could do but im not able to export or add an enum inside a func.

You cannot do this, no. (Well, the more complicated answer is that you can, but it’s a rather large hassle that’s only worth going through if there are no better options. See: _get_property_list Object — Godot Engine (stable) documentation in English)

A much better choice for this particular design is to have each item as a class, and make use of inheritance.

# item_data.gd
class_name ItemData
extends Resource

#These are the base item types and variables for all items
enum ItemType {RESOURCE, CONSUMABLE, EQUIPMENT, WEAPON}

@export var itemName: String
@export var stackable: bool
@export var stackCount: int
@export var itemValue: int
@export var itemIcon: Texture2D
@export_multiline var description: String

Then, for instance:

# item_data_consumable.gd
class_name ItemDataConsumable
extends ItemData

enum ConsumableType {FOOD, DRINK, POTION}

var type: ItemType:
  get:
    return ItemType.CONSUMABLE

@export var type: ConsumableType
@export var healAmount: int

Any variable that can hold an ItemData can hold an ItemConsumable or anything else that derives from it, as well. You can check the type of the item with ItemType, or, also, the is operator.

I hope this explains it a bit!

1 Like