A shop is one of the quickest ways to add depth to a game: collect coins, spend them on upgrades, see the number go down. This guide builds a Unity shop system from the ground up: a currency wallet, item data as ScriptableObjects, buy checks, a shop UI generated from a grid, owned item tracking and saved purchases. The logic is kept separate from the UI so you can reuse it for any kind of shop.
The Pieces
- Wallet holds the player’s currency and raises an event when it changes.
- ShopItem (ScriptableObject) describes something for sale: name, icon, price and whether it can be bought more than once.
- ShopManager knows which items are owned and decides whether a purchase is allowed.
- ShopUI only displays data and forwards button clicks. It never changes money itself.
Keeping the rules out of the UI means you can test buying without a single button, and a bug in the layout cannot give away free items.
The Wallet
using System;
using UnityEngine;
public class Wallet : MonoBehaviour
{
[SerializeField] int startingCoins = 100;
public int Coins { get; private set; }
public event Action<int> OnChanged;
void Awake()
{
Coins = startingCoins;
}
public bool CanAfford(int price) => Coins >= price;
public void Add(int amount)
{
Coins += amount;
OnChanged?.Invoke(Coins);
}
public bool TrySpend(int price)
{
if (price < 0 || Coins < price) return false;
Coins -= price;
OnChanged?.Invoke(Coins);
return true;
}
}
The setter is private, so nothing outside can write Coins directly. All changes go through Add and TrySpend. TrySpend checks and deducts in one call, which stops a double click from spending twice. The event lets any UI text update itself without checking every frame. If you already have a coin counter, the collectibles guide shows pickups that can call wallet.Add.
Shop Item Data
using UnityEngine;
[CreateAssetMenu(menuName = "Shop/Shop Item")]
public class ShopItem : ScriptableObject
{
public string id; // unique and never changes, used for saving
public string displayName;
[TextArea] public string description;
public Sprite icon;
public int price = 50;
public bool oneTimePurchase = true;
}
The id field matters. Save the id, not the asset name or the list index, because names get renamed and list order changes when you add items. Use short stable strings like speed_boots. The ScriptableObjects guide explains why this pattern works well for item data.
The Shop Logic
using System;
using System.Collections.Generic;
using UnityEngine;
public class ShopManager : MonoBehaviour
{
[SerializeField] Wallet wallet;
[SerializeField] List<ShopItem> stock = new List<ShopItem>();
readonly Dictionary<string, int> owned = new Dictionary<string, int>();
public IReadOnlyList<ShopItem> Stock => stock;
public Wallet Wallet => wallet;
public event Action<ShopItem> OnPurchased;
public int CountOwned(ShopItem item) =>
owned.TryGetValue(item.id, out int n) ? n : 0;
public bool IsOwned(ShopItem item) => CountOwned(item) > 0;
public bool CanBuy(ShopItem item)
{
if (item.oneTimePurchase && IsOwned(item)) return false;
return wallet.CanAfford(item.price);
}
public bool TryBuy(ShopItem item)
{
if (!CanBuy(item)) return false;
if (!wallet.TrySpend(item.price)) return false;
owned[item.id] = CountOwned(item) + 1;
OnPurchased?.Invoke(item);
return true;
}
}
Anything that reacts to a purchase, such as equipping boots, adding a potion to the inventory or playing a sound, subscribes to OnPurchased. The shop does not need to know what an item does. If you want items to go into a real inventory, link the two with the pattern in the inventory tutorial and call its add method from the event.
Building the Shop UI
Create a Canvas with a panel, then inside it a Scroll View or plain panel with a Grid Layout Group (or Vertical Layout Group) for the item cards. Make one card prefab with an Image for the icon, a TextMeshPro name, a price text and a Button. Add a TextMeshPro label near the top for the coin total. If TMP is new to you, see the TextMeshPro tutorial.
The card script displays one item and reports clicks:
using System;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
public class ShopCard : MonoBehaviour
{
[SerializeField] Image icon;
[SerializeField] TMP_Text nameText;
[SerializeField] TMP_Text priceText;
[SerializeField] Button buyButton;
[SerializeField] TMP_Text buyLabel;
public ShopItem Item { get; private set; }
public void Setup(ShopItem item, Action<ShopItem> onClick)
{
Item = item;
icon.sprite = item.icon;
nameText.text = item.displayName;
priceText.text = item.price.ToString();
buyButton.onClick.RemoveAllListeners();
buyButton.onClick.AddListener(() => onClick(item));
}
public void Refresh(bool canBuy, bool owned)
{
buyButton.interactable = canBuy;
buyLabel.text = owned ? "Owned" : "Buy";
}
}
The shop window builds all cards once and refreshes them whenever something changes:
using System.Collections.Generic;
using TMPro;
using UnityEngine;
public class ShopUI : MonoBehaviour
{
[SerializeField] ShopManager shop;
[SerializeField] ShopCard cardPrefab;
[SerializeField] Transform cardParent;
[SerializeField] TMP_Text coinsText;
readonly List<ShopCard> cards = new List<ShopCard>();
void Start()
{
foreach (var item in shop.Stock)
{
var card = Instantiate(cardPrefab, cardParent, false);
card.Setup(item, OnCardClicked);
cards.Add(card);
}
shop.Wallet.OnChanged += _ => Refresh();
shop.OnPurchased += _ => Refresh();
Refresh();
}
void OnCardClicked(ShopItem item)
{
shop.TryBuy(item); // the UI asks, the manager decides
}
void Refresh()
{
coinsText.text = shop.Wallet.Coins.ToString();
foreach (var card in cards)
card.Refresh(shop.CanBuy(card.Item), shop.IsOwned(card.Item) && card.Item.oneTimePurchase);
}
}
Buying greys out cards you cannot afford and relabels owned ones, with no per-frame polling. If cards do not appear after instantiating, check the parent and scale, as described in the UI not showing guide. If the buy buttons do nothing, see the buttons not clicking guide.
Saving Purchases
Players expect money and purchases to survive a restart. Add a small serializable class and two methods to ShopManager:
[Serializable]
public class ShopSave
{
public int coins;
public List<string> ids = new List<string>();
public List<int> counts = new List<int>();
}
public ShopSave Capture()
{
var s = new ShopSave { coins = wallet.Coins };
foreach (var kv in owned) { s.ids.Add(kv.Key); s.counts.Add(kv.Value); }
return s;
}
public void Restore(ShopSave s)
{
owned.Clear();
for (int i = 0; i < s.ids.Count; i++) owned[s.ids[i]] = s.counts[i];
// the wallet needs a SetCoins method for this
}
Unity’s JsonUtility cannot serialize a Dictionary, which is why the data is stored as two parallel lists. For Restore to work, add a SetCoins(int) method to Wallet that sets Coins and invokes OnChanged. Then pass ShopSave to JsonUtility.ToJson and write it with the approach in the JSON save system guide, or store it inside a slot as in the save slots guide. Call Capture() right after a purchase so a crash does not lose it.
Extending It
- Selling: add a
sellPriceto the item and aTrySellthat decrements the owned count and callswallet.Add. - Stackable consumables: set
oneTimePurchaseto false and useCountOwnedto show “x3”. - Stock limits and restocking: store remaining stock per item and reset it on a timer or each day.
- Tabs and categories: add an enum to
ShopItemand filter the list the UI builds. - Quests and rewards: pay out coins through
wallet.Addfrom your quest system.
🔧 UI kits and shop art
Icon packs and ready-made UI kits make a shop look finished quickly. See our recommended Asset Store tools.
Troubleshooting
Coins go negative or purchases go through twice
Something is changing Coins without checking. Keep the setter private and route everything through TrySpend.
NullReferenceException in ShopUI.Start
The shop, card prefab, parent or coins text is not assigned in the Inspector. Click the error to see the exact line, then check that reference.
All buy buttons buy the last item
A lambda captured a loop variable incorrectly. In the code above the item is passed through Setup, which avoids the problem. If you add listeners inline in the loop, copy the variable to a local first.
Cards stack on top of each other
The parent has no Layout Group, or the Layout Group’s Control Child Size settings conflict with your card’s size. Add a Grid Layout Group and set the Cell Size.
Purchases are lost after restarting
Ownership is only in memory. Call Capture after each purchase, write it to disk, and call Restore on startup before the UI refreshes.
Owned items reappear after adding new stock
You saved list indexes. Save the stable id instead, as above.
FAQ
Should the wallet be a singleton?
You can, but passing a reference in the Inspector is cleaner and easier to test. If many scripts need it, a ScriptableObject wallet asset shared across scenes is another option.
How do I add real-money purchases?
That is a separate system built on Unity In-App Purchasing and platform stores. Keep this in-game currency shop for soft currency and let the store only grant currency packs.
Can I use floats for currency?
Use integers. Floats collect rounding errors, and players never need half a coin.
How do I stop players cheating by editing the save file?
You cannot fully stop it in a single-player game. For competitive or online games, keep the wallet on a server. For offline games, light obfuscation is usually enough.
Does this work with 3D objects instead of icons?
Yes. Replace the icon with a render texture of a preview camera, or just use a pre-rendered sprite for each item.
Reader questions
Asked by readers of this article and answered by AI. Behavior can differ between Unity versions, so test in yours.




Leave a Reply