Shop and Inventory
Part of the Building Real Games section of Coddy's Unity journey. Lesson 57 of 60.
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
HardWrite Shop and ShopItem, saved with PlayerPrefs.
Shop: coins underCoins(new player:startCoins), shown asCoins: 100; Work addspay.ShopItem: owned whenOwned_Helmetis 1; labelHelmet: 40orHelmet: owned; clickable while not owned and affordable; a click buys.inventoryText:Inventory: Helmet, CapeorInventory: empty. Save and redraw on every change.
Press Play, shop, 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;
}
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 SwapPractice on your own: Unity playground