Games
Inventory Systems
C#
C# Harness Tested (Unity Stubs)
Unity C# Stackable Inventory Container
Data-driven Unity C# inventory system using ScriptableObject item definitions, stack merging, slot capacity limits, and change events.
Architecture & Runtime Preview
Unity 2022+ / Unity 6Unity C# ScriptableObject + container component — inspect source tabs and attach InventoryContainer to a player GameObject.
- 1ItemDefinition (ScriptableObject: Id, MaxStack)
- 2InventoryContainer.TryAdd(item, count) -> merge existing stacks -> allocate free slots
- 3OnInventoryChanged event -> UI Slot Grid
Example Project Integration: Copy into Assets/Scripts/Inventory/ inside a Unity project.
Source Code (2 files)
using UnityEngine;
namespace OtterLibrary.Inventory
{
[CreateAssetMenu(menuName = "Otter Library/Item Definition")]
public sealed class ItemDefinition : ScriptableObject
{
public string ItemId = "potion_health";
public string DisplayName = "Health Potion";
[Min(1)] public int MaxStack = 10;
}
}
using System;
using System.Collections.Generic;
using UnityEngine;
namespace OtterLibrary.Inventory
{
[Serializable]
public sealed class InventorySlot
{
public ItemDefinition Item;
public int Quantity;
}
public sealed class InventoryContainer : MonoBehaviour
{
[Min(1)] [SerializeField] private int capacity = 16;
private readonly List<InventorySlot> _slots = new();
public event Action OnInventoryChanged;
public IReadOnlyList<InventorySlot> Slots => _slots;
public int Capacity => capacity;
public bool TryAdd(ItemDefinition item, int quantity)
{
if (item == null || quantity <= 0) return false;
int remaining = quantity;
foreach (var slot in _slots)
{
if (slot.Item != item || slot.Quantity >= item.MaxStack) continue;
int space = item.MaxStack - slot.Quantity;
int toAdd = Math.Min(space, remaining);
slot.Quantity += toAdd;
remaining -= toAdd;
if (remaining == 0) break;
}
while (remaining > 0 && _slots.Count < capacity)
{
int toAdd = Math.Min(item.MaxStack, remaining);
_slots.Add(new InventorySlot { Item = item, Quantity = toAdd });
remaining -= toAdd;
}
if (remaining < quantity) OnInventoryChanged?.Invoke();
return remaining == 0;
}
public bool TryConsume(ItemDefinition item, int quantity)
{
if (item == null || quantity <= 0) return false;
int available = 0;
foreach (var slot in _slots) if (slot.Item == item) available += slot.Quantity;
if (available < quantity) return false;
int remaining = quantity;
for (int i = _slots.Count - 1; i >= 0 && remaining > 0; i--)
{
if (_slots[i].Item != item) continue;
int take = Math.Min(_slots[i].Quantity, remaining);
_slots[i].Quantity -= take;
remaining -= take;
if (_slots[i].Quantity == 0) _slots.RemoveAt(i);
}
OnInventoryChanged?.Invoke();
return true;
}
}
}
Installation & Usage
Copy ItemDefinition.cs and InventoryContainer.cs into Assets/Scripts/Inventory/ in your Unity project.
Create item assets via Right-Click -> Create -> Otter Library -> Item Definition, attach InventoryContainer to a GameObject, and call TryAdd / TryConsume.