Menu
CoddyTech

Recap: Item Database

Part of the Game Architecture in Unity section of Coddy's Unity journey. Lesson 23 of 50.

challenge icon

Challenge

Medium

The blacksmith's shop sells from an item database that every shop in the game will share. Write the two asset types and the Shop:

  • ItemData (in ItemData.cs): a ScriptableObject with a Create menu entry and the public fields itemName (a string) and price (an int).
  • ItemDatabase (in ItemDatabase.cs): a ScriptableObject with a Create menu entry and one public field, items, a list of ItemData.
  • Shop gets a public field database of type ItemDatabase. itemText shows the selected item as Iron Sword: 30 gold, starting with the first item, and goldText shows the gold as Gold: 50.
  • The right arrow selects the next item, and after the last one the first again; the left arrow goes the other way, from the first item to the last.
  • Space buys the selected item. An item the player already bought logs Already owned: Iron Sword. An item that costs more than the gold logs Not enough gold for Iron Sword. Otherwise the gold drops by the price, the item is owned, the texts update and the Console says Bought Iron Sword.
  • Keep what was bought in the Shop. The assets stay as they are: the database is shared, and in the Editor a change to an asset outlives Play mode.

The project has four ItemData assets (Iron Sword 30, Oak Shield 20, Healing Potion 10, Long Bow 45), a Database asset that lists them in that order, and the Inspector puts the Database in the Shop's database field. Press Play, go shopping, then Check.

Try it yourself

using UnityEngine;
using UnityEngine.InputSystem;
using TMPro;

public class Shop : MonoBehaviour
{
    public TMP_Text itemText;
    public TMP_Text goldText;
    public int gold = 50;

    // The database field, browsing with the arrows and buying with Space go here
}

All lessons in Game Architecture in Unity