Crafting Recipes
Part of the Game Architecture in Unity section of Coddy's Unity journey. Lesson 63 of 64.
Challenge
HardGive CraftingBench its recipes.
- Add serializable
Ingredient(publicitem,amount) andRecipe(publicresult,List<Ingredient> needs), and a publicList<Recipe> recipes. - In
Start,recipeButtons[i]callsCraft(i). public void Craft(int index): with every need held, remove them, add one result, logCrafted Axe.Refreshmakes 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
1Components, Not Hierarchies
Small ComponentsA Base Enemy ScriptAbstract ComponentsComponents Working TogetherRecap: Modular TurretRecap: Twin Cannon4Serialized Data
Serializable ClassesLists in the InspectorEnums in the InspectorRecap: Loot TableRecap: Roll the Loot2Interfaces in Unity
IDamageableInterfaces and TryGetComponentGetComponentsRecap: Interact KeyRecap: Nearest in ReachPractice on your own: Unity playground