How to autoload a resource? Design question

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

I am building an inventory of items which I’d like to be available globally as a singleton. I created an Item class inheriting from Resource, and InventoryResource as:

extends Resource
class_name InventoryResource

export var items: Dictionary = {}

where I’m planning to put the items available by the user. I will be trying to read the inventory from disk and if it’s not there creating a new one.

Apart from this, I would like to have a couple of functions for interacting with the items (adding items, emitting signals). I see two options of doing this:

  1. add the logic to the InventoryResource class. This way the logic will be living close the the data (good), but I’ll need to have the loading code in a separate singleton class (as resources can’t be autoloaded) or having the loading logic repeated in every place that needs inventory access. I also don’t like the fact that I’ll need to explicitly load the inventory everywhere and am a bit worried whether the inventory logic will be stored (and reloaded) together with data or not and if this will create multiple copies of the inventory in memory.

  2. Keep InventoryResource data only and put the logic (including loading logic) into a separate, autoloaded class. This way I have a single way for accessing the inventory, but the inventory logic is kept separate from the data.

Do you have any opinion on which option is preferable? Is there some better way to do this that I missed?

I saw this related question, but it’s on how to technically make it work, and I wonder more about the code design.

:bust_in_silhouette: Reply From: IHate

I posted this question and came up with an answer for my specific problem but is something you could use: what's the best way to handle every tile's interactions data. - Archive - Godot Forum

In the end it depends on how much logic each item has if you can pile each item in a specific category and that category would use the same functions as other items in that category you could make a var item_type on the item base resource and use match in to call the functions needed. If the items don’t share functions even in the same category I would go with the posted answer

Thanks for commenting, but in my case there are no different items having different logic; rather there is some common logic for the whole inventory which can either live together with the resource or on some singleton class

sygi | 2021-03-15 19:22