Menu
CoddyTech

Crafting Recipes

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

challenge icon

Challenge

Hard

Give CraftingBench its recipes.

  1. Add serializable Ingredient (public item, amount) and Recipe (public result, List<Ingredient> needs), and a public List<Recipe> recipes.
  2. In Start, recipeButtons[i] calls Craft(i).
  3. public void Craft(int index): with every need held, remove them, add one result, log Crafted Axe.
  4. Refresh makes a button clickable only while its recipe can be crafted.

Press Play and craft a raft. Then Check.

Try it yourself

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;

public class CraftingBench : MonoBehaviour
{
    [SerializeField] private Inventory inventory;
    [SerializeField] private Button[] recipeButtons;
    [SerializeField] private Button woodButton;
    [SerializeField] private Button stoneButton;
    [SerializeField] private TMP_Text inventoryText;

    void OnEnable()
    {
        inventory.Changed += Refresh;
    }

    void OnDisable()
    {
        inventory.Changed -= Refresh;
    }

    void Start()
    {
        woodButton.onClick.AddListener(() => inventory.Add("Wood", 1));
        stoneButton.onClick.AddListener(() => inventory.Add("Stone", 1));
        // Recipes: recipe button i crafts recipe i
        Refresh();
    }

    void Refresh()
    {
        // Recipes: a recipe button is clickable only while its recipe can be crafted
        inventoryText.text = "Inventory: " + inventory.Describe();
    }
}

All lessons in Game Architecture in Unity

Practice on your own: Unity playground