Menu
CoddyTech

Shop and Inventory

Part of the Building Real Games section of Coddy's Unity journey. Lesson 54 of 56.

Between levels, the hero visits a shop. Three items wait on the shelf, a Helmet, Boots and a Cape, each on a button showing its price, and a Work button earns coins for the ones the hero cannot afford yet. What the hero buys goes into the inventory listed at the bottom, and the coins left and the items owned are still there the next time the game starts.

Write two scripts: Shop on the Shop object, and ShopItem on each item's button.

challenge icon

Challenge

Hard

The Inspector gives Shop startCoins (100), pay (25), coinsText, inventoryText, workButton and items, the three ShopItems in shelf order. It gives each ShopItem its itemName and price (Helmet 40, Boots 60, Cape 120), label (the text on its button) and shop.

  • The coins are saved under the key Coins; a player with nothing saved starts with startCoins. coinsText shows them, as Coins: 100.
  • Each click on Work earns pay coins.
  • An item is owned when the key Owned_ plus its name (Owned_Helmet) holds 1. Its label reads Helmet: 40 while it is for sale and Helmet: owned once it is owned.
  • An item's button can be clicked only while the item is not owned and the player has at least its price. Clicking it buys the item: the price comes off the coins and the item is owned.
  • inventoryText lists the owned items in shelf order, as Inventory: Helmet, Cape, or reads Inventory: empty.
  • Every change is saved at once, and every text and button shows the new state.

Press Play, shop and work, press Stop and Play again, then Check.

Try it yourself

using UnityEngine;
using UnityEngine.UI;
using TMPro;

public class Shop : MonoBehaviour
{
    public int startCoins = 100;
    public int pay = 25;
    public TMP_Text coinsText;
    public TMP_Text inventoryText;
    public Button workButton;
    public ShopItem[] items;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Building Real Games