Inventory System
A fully networked inventory system with item stacking, drag-and-drop slots, equipment, sorting, and a ScriptableObject item database. Uses SyncList and SyncDictionary for real-time sync across all clients.
Overview โ script responsibilities
This example is split into six focused scripts. Each script has exactly one job, which makes it easy to swap out or extend individual pieces without touching the rest of the system.
- ItemData โ a ScriptableObject that holds all the static data for one item type: its ID, display name, icon, max stack size, and equipment slot.
- ItemDatabase โ a ScriptableObject that owns every
ItemDataasset and provides fast string-key lookups at runtime. - InventoryItem โ a tiny network-serializable struct that represents one occupied slot: just an
itemIdstring and aquantity. - PlayerInventory โ the
NetworkBehaviourthat owns the authoritative slot list. All mutations go through[ServerRpc]so the server is always in control. - InventorySlotUI โ one grid cell in the UI. Handles drag-and-drop events and fires RPC requests to
PlayerInventory. - InventoryUI โ the panel controller. Instantiates all slot widgets on
Startand re-renders them wheneveronInventoryChangedfires.
Inventory System โ component map โ hover a node to highlight its connections
Script 1 โ ItemData (ScriptableObject)
ItemData is a pure data container. You create one asset per item type in the Unity Editor (right-click โ PurrNet โ Item Data) and fill in its fields. Because it is a ScriptableObject it lives in your project as an asset file, never travels over the network, and can be referenced by the database without duplicating data.
The itemIdfield is the system's primary key. Every other script uses this string to look up item properties at runtime. Keep it short, lowercase, and unique โ e.g. "sword_iron", "potion_health".
using UnityEngine;
[CreateAssetMenu(fileName = "Item", menuName = "PurrNet/Item Data")]
public class ItemData : ScriptableObject
{
public string itemId; // unique key used in InventoryItem
public string displayName;
[TextArea] public string description;
public Sprite icon;
[Min(1)] public int maxStackSize = 1;
public bool isEquippable;
public EquipmentSlotType equipmentSlot;
public ItemRarity rarity;
}
public enum ItemRarity { Common, Uncommon, Rare, Epic, Legendary }
public enum EquipmentSlotType { None, Weapon, Helmet, Chest, Legs, Boots }Script 2 โ ItemDatabase (ScriptableObject)
ItemDatabase is your item catalogue. Drag all ItemData assets into its _items array in the Inspector. On OnEnable it builds a fast Dictionary<string, ItemData> lookup so that Get(itemId) is O(1) โ important when the server processes many add/remove operations per frame.
Both PlayerInventory and the UI scripts hold a serialized reference to the same ItemDatabase asset. There is only ever one instance, so data is never out of sync between server and client (they both read from identical assets that ship with the game build).
using UnityEngine;
using System.Collections.Generic;
[CreateAssetMenu(fileName = "ItemDatabase", menuName = "PurrNet/Item Database")]
public class ItemDatabase : ScriptableObject
{
[SerializeField] private ItemData[] _items;
private Dictionary<string, ItemData> _lookup;
private void OnEnable()
{
_lookup = new Dictionary<string, ItemData>();
foreach (var item in _items)
if (item != null && !string.IsNullOrEmpty(item.itemId))
_lookup[item.itemId] = item;
}
public ItemData Get(string itemId) =>
!string.IsNullOrEmpty(itemId) && _lookup.TryGetValue(itemId, out var d) ? d : null;
public IEnumerable<ItemData> All => _items;
}Script 3 โ InventoryItem (Network Struct)
InventoryItem is deliberately tiny. It stores only the string ID and the quantity โ nothing else. This keeps the per-slot payload as small as possible when PurrNet serializes the SyncList delta. All display data (icon, name, description) is resolved locally by calling ItemDatabase.Get(itemId).
The IPackedAutointerface tells PurrNet's BitPacker to automatically generate an efficient serializer for this struct. The IsEmpty computed property is a convenience helper used throughout the other scripts to avoid null checks.
using System;
[Serializable]
public struct InventoryItem : IPackedAuto
{
public string itemId;
public int quantity;
public bool IsEmpty => string.IsNullOrEmpty(itemId) || quantity <= 0;
public static readonly InventoryItem Empty = default;
}Script 4 โ PlayerInventory (Networked)
This is the heart of the system. It extends NetworkBehaviour and owns two networked collections: SyncList<InventoryItem> for the bag slots and SyncDictionary<EquipmentSlotType, InventoryItem> for the equipped items. PurrNet automatically replicates every change to all connected observers โ you never write send/receive code manually.
Every write method (CmdAddItem, CmdRemoveItem, etc.) is decorated with [ServerRpc(requireOwnership: true)]. This means the message is sent to the server, the server validates and applies the change, and the updated SyncListdata flows back out to all observers. Clients can read the inventory freely but can never write to someone else's slots.
using PurrNet;
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class PlayerInventory : NetworkBehaviour
{
[SerializeField] private ItemDatabase _database;
[SerializeField] private int _slotCount = 24;
private SyncList<InventoryItem> _slots = new();
private SyncDictionary<EquipmentSlotType, InventoryItem> _equipped = new();
// Events โ fire on ALL clients
public event Action onInventoryChanged;
public event Action<EquipmentSlotType, InventoryItem> onEquipmentChanged;
// โโ Lifecycle โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
protected override void OnSpawned(bool asServer)
{
base.OnSpawned(asServer);
if (asServer)
{
for (int i = 0; i < _slotCount; i++)
_slots.Add(InventoryItem.Empty);
}
_slots.onChanged += _ => onInventoryChanged?.Invoke();
_equipped.onChanged += (k, v, _) => onEquipmentChanged?.Invoke(k, v);
}
protected override void OnDespawned(bool asServer)
{
base.OnDespawned(asServer);
_slots.onChanged -= _ => onInventoryChanged?.Invoke();
_equipped.onChanged -= (k, v, _) => onEquipmentChanged?.Invoke(k, v);
}
// โโ Read API (safe to call from any client) โโโโโโโโโโโโโโโโโโโโโโโโโโโโ
public IReadOnlyList<InventoryItem> GetInventory() => _slots;
public InventoryItem GetEquipped(EquipmentSlotType slot) =>
_equipped.TryGetValue(slot, out var item) ? item : InventoryItem.Empty;
public bool HasItem(string itemId, int qty = 1)
{
int total = _slots.Where(s => s.itemId == itemId).Sum(s => s.quantity);
return total >= qty;
}
// โโ Write API (ServerRpc โ only owner can request) โโโโโโโโโโโโโโโโโโโโ
[ServerRpc(requireOwnership: true)]
public void CmdAddItem(string itemId, int quantity = 1)
{
var data = _database.Get(itemId);
if (data == null || quantity <= 0) return;
int remaining = quantity;
// Pass 1: fill existing stacks
for (int i = 0; i < _slots.Count && remaining > 0; i++)
{
if (_slots[i].itemId != itemId) continue;
int space = data.maxStackSize - _slots[i].quantity;
if (space <= 0) continue;
int add = Mathf.Min(space, remaining);
_slots[i] = new InventoryItem { itemId = itemId, quantity = _slots[i].quantity + add };
remaining -= add;
}
// Pass 2: fill empty slots
for (int i = 0; i < _slots.Count && remaining > 0; i++)
{
if (!_slots[i].IsEmpty) continue;
int add = Mathf.Min(data.maxStackSize, remaining);
_slots[i] = new InventoryItem { itemId = itemId, quantity = add };
remaining -= add;
}
// remaining > 0 means inventory is full โ optionally notify caller
}
[ServerRpc(requireOwnership: true)]
public void CmdRemoveItem(string itemId, int quantity = 1)
{
if (quantity <= 0) return;
int remaining = quantity;
for (int i = _slots.Count - 1; i >= 0 && remaining > 0; i--)
{
if (_slots[i].itemId != itemId) continue;
if (_slots[i].quantity <= remaining)
{
remaining -= _slots[i].quantity;
_slots[i] = InventoryItem.Empty;
}
else
{
_slots[i] = new InventoryItem { itemId = itemId, quantity = _slots[i].quantity - remaining };
remaining = 0;
}
}
}
[ServerRpc(requireOwnership: true)]
public void CmdMoveItem(int fromIndex, int toIndex)
{
if ((uint)fromIndex >= (uint)_slots.Count) return;
if ((uint)toIndex >= (uint)_slots.Count) return;
var from = _slots[fromIndex];
var to = _slots[toIndex];
// Try stack if same item
if (!from.IsEmpty && from.itemId == to.itemId)
{
var data = _database.Get(from.itemId);
if (data != null)
{
int total = from.quantity + to.quantity;
_slots[toIndex] = new InventoryItem { itemId = to.itemId, quantity = Mathf.Min(total, data.maxStackSize) };
_slots[fromIndex] = total > data.maxStackSize
? new InventoryItem { itemId = from.itemId, quantity = total - data.maxStackSize }
: InventoryItem.Empty;
return;
}
}
// Otherwise swap
_slots[fromIndex] = to;
_slots[toIndex] = from;
}
[ServerRpc(requireOwnership: true)]
public void CmdEquipItem(int slotIndex)
{
if ((uint)slotIndex >= (uint)_slots.Count) return;
var item = _slots[slotIndex];
if (item.IsEmpty) return;
var data = _database.Get(item.itemId);
if (data == null || !data.isEquippable || data.equipmentSlot == EquipmentSlotType.None) return;
// Swap equipped <-> slot
var currentEquipped = GetEquipped(data.equipmentSlot);
_slots[slotIndex] = currentEquipped;
_equipped[data.equipmentSlot] = item;
}
[ServerRpc(requireOwnership: true)]
public void CmdSortInventory()
{
var sorted = _slots
.Where(s => !s.IsEmpty)
.OrderBy(s => s.itemId)
.ThenByDescending(s => s.quantity)
.ToList();
for (int i = 0; i < _slots.Count; i++)
_slots[i] = i < sorted.Count ? sorted[i] : InventoryItem.Empty;
}
}Only the owner can modify their inventory
[ServerRpc(requireOwnership: true)]. This means only the player who owns the inventory object can call AddItem, RemoveItem, etc. The server validates and applies every change.maxStackSize is enforced server-side
[ServerRpc]. The server reads maxStackSize from ItemDatabase and enforces it before any write completes.SyncDictionary callbacks have a third parameter
onChanged callback on SyncDictionary includes a SyncDictionaryChange reason parameter. Ignore it with _ if you just need to react to any change.Script 5 โ InventorySlotUI (Drag & Drop)
InventorySlotUI is a plain MonoBehaviour โ it does not extend NetworkBehaviour. Its job is purely presentational: display the correct icon and quantity text, and translate UI drag-and-drop events into RPC calls on the local player's PlayerInventory.
When the player drags one slot onto another, OnDrop fires and immediately calls CmdMoveItem. The server processes the swap and the SyncList update propagates back to all clients โ including the dragging player โ so the UI always reflects authoritative state rather than a client-side prediction.
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using TMPro;
public class InventorySlotUI : MonoBehaviour,
IBeginDragHandler, IDragHandler, IEndDragHandler, IDropHandler, IPointerClickHandler
{
[SerializeField] private Image _iconImage;
[SerializeField] private TextMeshProUGUI _quantityText;
[SerializeField] private Image _highlight;
private PlayerInventory _inventory;
private ItemDatabase _database;
private int _slotIndex;
private static InventorySlotUI _dragging;
private static GameObject _dragGhost; // spawned at cursor while dragging
public void Setup(PlayerInventory inventory, ItemDatabase database, int index)
{
_inventory = inventory;
_database = database;
_slotIndex = index;
}
public void Refresh(InventoryItem item)
{
bool empty = item.IsEmpty;
_iconImage.enabled = !empty;
if (!empty)
{
var data = _database.Get(item.itemId);
_iconImage.sprite = data?.icon;
}
_quantityText.text = (!empty && item.quantity > 1) ? item.quantity.ToString() : "";
}
// โโ Drag & Drop โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
public void OnBeginDrag(PointerEventData e)
{
_dragging = this;
_iconImage.color = new Color(1, 1, 1, 0.4f); // dim slot
// Optionally spawn a drag ghost here
}
public void OnDrag(PointerEventData e)
{
// Move ghost with cursor if you spawned one
}
public void OnEndDrag(PointerEventData e)
{
_iconImage.color = Color.white;
_dragging = null;
}
public void OnDrop(PointerEventData e)
{
if (_dragging == null || _dragging == this) return;
// Send move request to server
_inventory.CmdMoveItem(_dragging._slotIndex, _slotIndex);
}
public void OnPointerClick(PointerEventData e)
{
if (e.button == PointerEventData.InputButton.Right)
_inventory.CmdEquipItem(_slotIndex); // right-click to equip
}
}Always use itemId strings, never asset references
InventoryItem stores a string ID, not a reference to ItemData. This keeps the struct small and network-serializable. Always look up ItemData via ItemDatabase.Get(itemId) when you need the display data.Script 6 โ InventoryUI (Panel Controller)
InventoryUI is the top-level panel manager. On Start it reads the slot count from PlayerInventory.GetInventory(), instantiates exactly that many InventorySlotUI prefabs, and positions them in the grid container.
After setup it simply listens to onInventoryChanged and calls RefreshAll() whenever the list changes. Because PurrNet fires this event on every client automatically, the UI stays live across all machines with a single subscription.
using UnityEngine;
using System.Collections.Generic;
public class InventoryUI : MonoBehaviour
{
[SerializeField] private PlayerInventory _inventory;
[SerializeField] private ItemDatabase _database;
[SerializeField] private InventorySlotUI _slotPrefab;
[SerializeField] private Transform _slotContainer;
[SerializeField] private UnityEngine.UI.Button _sortButton;
private readonly List<InventorySlotUI> _slots = new();
private void Start()
{
// Build slots
var items = _inventory.GetInventory();
for (int i = 0; i < items.Count; i++)
{
var slot = Instantiate(_slotPrefab, _slotContainer);
slot.Setup(_inventory, _database, i);
slot.Refresh(items[i]);
_slots.Add(slot);
}
_inventory.onInventoryChanged += RefreshAll;
_sortButton.onClick.AddListener(() => _inventory.CmdSortInventory());
}
private void OnDestroy()
{
if (_inventory != null)
_inventory.onInventoryChanged -= RefreshAll;
}
private void RefreshAll()
{
var items = _inventory.GetInventory();
for (int i = 0; i < _slots.Count; i++)
_slots[i].Refresh(i < items.Count ? items[i] : InventoryItem.Empty);
}
}API Reference
All public surface of PlayerInventory that you will call from UI scripts or game logic:
| Parameter | Type | Default | Description |
|---|---|---|---|
GetInventory() | IReadOnlyList<InventoryItem> | โ | Returns the current list of all slots. Read-only; clients use this for display. |
AddItem(string itemId, int quantity) | [ServerRpc] void | โ | Stacks into existing slots first, then fills empty slots. Respects maxStackSize from ItemData. |
RemoveItem(string itemId, int quantity) | [ServerRpc] void | โ | Removes quantity from back to front. Partial stacks are consumed first. |
MoveItem(int from, int to) | [ServerRpc] void | โ | Swaps two slots. If same item, attempts to stack up to maxStackSize. |
EquipItem(int slotIndex) | [ServerRpc] void | โ | Equips the item at slotIndex. Swaps with currently equipped item in that equipment slot. |
SortInventory() | [ServerRpc] void | โ | Sorts all slots alphabetically by itemId then by quantity descending. Empty slots sink to the bottom. |
onInventoryChanged | event Action | โ | Fires on all clients whenever any slot changes. |
onEquipmentChanged | event Action<EquipmentSlotType, InventoryItem> | โ | Fires when equipment changes in any slot. |
Scene Setup
Scene Setup
- Create
ItemDataassets for each item (right-click โ PurrNet โ Item Data). - Create an
ItemDatabaseasset and drag allItemDataassets into its_itemsarray. - Assign
ItemDatabasetoPlayerInventoryin the Inspector. - Assign
PlayerInventoryandItemDatabasetoInventoryUI. - Register the player prefab in NetworkManager โ Network Prefabs.