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
HardThe 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 withstartCoins.coinsTextshows them, asCoins: 100. - Each click on Work earns
paycoins. - An item is owned when the key
Owned_plus its name (Owned_Helmet) holds 1. Its label readsHelmet: 40while it is for sale andHelmet: ownedonce 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.
inventoryTextlists the owned items in shelf order, asInventory: Helmet, Cape, or readsInventory: 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;
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Building Real Games
2Buttons and Screens
Buttons and onClickLambdasWiring in the InspectorPanels On and OffHealth BarsRecap: Upgrade Shop5Saving with PlayerPrefs
Save a NumberLoad with a DefaultHigh ScoreSave SettingsRecap: Coins in the Bank3The Game Manager
One Script Runs the GameThe SingletonGame StatesSwitching on the StateRecap: Round Manager6Project: Endless Runner
Three LanesObstacles Ahead9The New Input System
Two Input SystemsKeyboard and MousePressed This FrameInput ActionsRecap: Input Swap