Adding items to a resource/array when pressing a button

Godot Version

Godot 4.2

Question

Hello! I’m another newbie, struggling with something basic. I’m making an inventory by using custom resources, and want to add an item to the inventory by simply pressing a button in a menu.

Tutorials have helped make the inventory itself so far, but I can’t seem to actually add anything to it when pressing the button, and I know I’m lacking some real basic understanding of this that that tutorials aren’t helping with, as they all approach it from different angles.

What I have so far:

The inventory resource, with some randomly pre-filled items for testing. These show up fine when I open the inventory ingame:
billede

The code for pressing the button, in a script attached to said button:


The test prints work fine, it seems to call the item in the exported variable without issue.

The code in the inventory script to try and add the item. Again, the print works fine with the right item name from the resource, but when I open the inventory ingame, nothing has been added:
billede

Just in case, here’s also most of my code for showing the inventory, in case something is wrong there or not updating right:

What could I be missing?

You need to save the inventory .tres to load it again. Check ResourceSaver.save

1 Like

Interesting, haven’t seen that brought up before!

I’m not entirely sure I understand how to use it, though. Where would I need to add that in? In the add item function? And does it change how to load the contents of the resource later?

Depends what you are trying to do. Is this to keep inventory in memory while game is running? Or do you need to reference it later on restart.

If in memory only then, you claim your test is adding the item. That test only shows the item passed to function correctly. Dump out the inventory instead after the append. If you don’t see it there it may mean there is an append error. Check the errors in debug.

So in your case, in the add_item() method, use something like this:

prints(inventory_contents)

If you don’t see it, it means there was a problem with append. Usually just a bad value.

1 Like

Oh dang, that was a much better way of testing it! I know what’s wrong now, it got added fine, but I messed up the array size when it shows the inventory window.

Thank you so much! So simple but helped a lot :slight_smile:

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.