Menu
CoddyTech

Crafting Bench

Part of the Game Architecture in Unity section of Coddy's Unity journey. Lesson 62 of 64.

In a survival game, a crafting bench turns what you gather into things you can use. Two buttons gather wood and stone, and three recipes turn them into more: two wood make a plank, a plank and two stone make an axe, four planks make a raft. A recipe's button can be pressed only while the inventory holds everything the recipe needs, and crafting uses those things up. The recipes are data filled in on the bench in the Inspector, so a new recipe needs no new code. The inventory announces every change to whoever is listening, and it is saved as JSON each time it changes, so quitting the game loses nothing.

Two lessons build it. This one writes the Inventory, on the Backpack; the bench's recipes come next.

challenge icon

Challenge

Hard

Part 1: fill in the Inventory; gathering is ready.

  1. Add serializable ItemStack (public item, count) and InventoryData (public List<ItemStack> stacks).
  2. Fill in Count, Add, Remove (a stack at 0 leaves) and Describe: Wood 3, Plank 1 or empty.
  3. Each change saves inventory.json in Application.persistentDataPath and raises Changed; Awake loads it.

Press Play, gather, then replay: the wood is back. Then Check.

Try it yourself

using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

// ItemStack and InventoryData go here

public class Inventory : MonoBehaviour
{
    public event Action Changed;

    void Awake()
    {
        // Load inventory.json when it exists
    }

    public int Count(string item)
    {
        return 0;
    }

    public void Add(string item, int amount)
    {
    }

    public void Remove(string item, int amount)
    {
    }

    public string Describe()
    {
        return "empty";
    }
}

All lessons in Game Architecture in Unity

Practice on your own: Unity playground