How to build stackable inventory for a game in C#

A while back, someone on Reddit asked how to write some C# code to handle the inventory for an RPG game, with the ability to stack similar items into the same inventory slot.

I wrote some code to do this, and added the ability for different types of items to be stacked to different limits, before they needed to fill another inventory slot. For example, you could say that plants can be stacked to 50 (per inventory slot), while potions could only be stacked to 10.

Here’s what I wrote to show how to do that.

Defining the inventory item classes

The base class for all inventory items is:


The different types of items will inherit from this class. If you want the item to be stackable, you can set the MaximumStackableQuantity to a value other than 1 (which is the default).

Plant.cs – which can be stacked to 50 per inventory slot

Potion.cs – which can be stacked to 10 per inventory slot

Weapon.cs – which cannot be stacked, so its MaximumStackableQuantity is 1

This assumes that, somewhere in your program, you have a place to hold all the different types of items that exist in your game world.

So, somewhere, you’d have a static class (or some other thing that is always available, everywhere in your program), with lists of all the types of plants, potions, or weapons that the player could every encounter.


Adding an item to the player’s inventory

Now we need a place to store the player’s inventory.

For this, I’ve created the InventorySystem class. It has a public InventoryRecords list that contains everything the player currently holds in their inventory.

When we want to add something to the player’s inventory, we call the AddItem method, passing in the item object, and the amount you’re trying to add to the player’s inventory.

In the AddItem method, we do this by trying to find an inventory slot that already contains an item with the same ID as the item passed into the method, and hasn’t reached the maximum stack size. If we have one, we put as much in that inventory slot as possible. If we reach the limit, and still have more to add, or if there isn’t a partially-filled slot with that item type, we try to add the remaining quantity to another slot. If there isn’t another slot available, we throw an exception.

Throwing an exception isn’t what you really want to do, because those are really used for breaking errors – and this is not really an error.

It would be better to create and raise an event for OnInventoryCannotAcceptMoreItems, passing it the item and remaining quantity. With that, your user interface could display a message such as, “Your inventory is full, and you are unable to pick up 3 healing potions.”




Leave a Reply

Your email address will not be published. Required fields are marked *