Recap: Buy from the Shop
Part of the Game Architecture in Unity section of Coddy's Unity journey. Lesson 29 of 64.
This chapter moved data into assets that many objects share. The shop's items are such assets, so what the player buys belongs in the Shop, never in them.
Challenge
EasyLet Space buy the selected item, leaving the assets alone.
- Keep the bought items in
List<ItemData> ownedin the Shop. - On Space, an owned item logs
Already owned: Iron Sword; one costing more thangoldlogsNot enough gold for Iron Sword. - Otherwise take the price off
gold, add it toowned, logBought Iron Swordand update the texts.
Press Play and buy the Long Bow. Then Check.
Try it yourself
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
using TMPro;
public class Shop : MonoBehaviour
{
public ItemDatabase database;
public TMP_Text itemText;
public TMP_Text goldText;
public int gold = 50;
private int index;
void Start()
{
Show();
}
void Update()
{
if (Keyboard.current.rightArrowKey.wasPressedThisFrame)
{
index = (index + 1) % database.items.Count;
Show();
}
if (Keyboard.current.leftArrowKey.wasPressedThisFrame)
{
index = (index - 1 + database.items.Count) % database.items.Count;
Show();
}
// Space: buy the selected item
}
void Show()
{
ItemData item = database.items[index];
itemText.text = item.itemName + ": " + item.price + " gold";
goldText.text = "Gold: " + gold;
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Game Architecture in Unity
1Components, Not Hierarchies
Small ComponentsA Base Enemy ScriptAbstract ComponentsComponents Working TogetherRecap: Modular TurretRecap: Twin Cannon4Serialized Data
Serializable ClassesLists in the InspectorEnums in the InspectorRecap: Loot TableRecap: Roll the Loot2Interfaces in Unity
IDamageableInterfaces and TryGetComponentGetComponentsRecap: Interact KeyRecap: Nearest in Reach5ScriptableObjects
Data AssetsWeapon StatsShared SettingsSave the WindWaves as DataRecap: Item DatabaseRecap: Buy from the ShopPractice on your own: Unity playground