Menu
CoddyTech

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 icon

Challenge

Easy

Let Space buy the selected item, leaving the assets alone.

  1. Keep the bought items in List<ItemData> owned in the Shop.
  2. On Space, an owned item logs Already owned: Iron Sword; one costing more than gold logs Not enough gold for Iron Sword.
  3. Otherwise take the price off gold, add it to owned, log Bought Iron Sword and 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;
    }
}
quiz iconTest yourself

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

All lessons in Game Architecture in Unity

Practice on your own: Unity playground