Recap: Item Database
Part of the Game Architecture in Unity section of Coddy's Unity journey. Lesson 23 of 50.
Challenge
MediumThe 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 fieldsitemName(a string) andprice(an int).ItemDatabase(in ItemDatabase.cs): a ScriptableObject with a Create menu entry and one public field,items, a list of ItemData.Shopgets a public fielddatabaseof type ItemDatabase.itemTextshows the selected item asIron Sword: 30 gold, starting with the first item, andgoldTextshows the gold asGold: 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 logsNot enough gold for Iron Sword. Otherwise the gold drops by the price, the item is owned, the texts update and the Console saysBought 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
1Components, Not Hierarchies
Small ComponentsA Base Enemy ScriptAbstract ComponentsComponents Working TogetherRecap: Modular Turret10Project: Arena Survivor
The HeroEnemy Types