# 2. Recipe Assets and Recipe Book Part of [[Crafting System]]. Prev: [[1. Crafting Design and the Level Up! Lens]]. Next: [[3. Crafting Service and Inventory Transactions]]. > [!warning] Code not compiled > Written against the Unity 6000.5 Scripting API (`ScriptableObject`, `CreateAssetMenu`, `OnValidate`, `AssetDatabase.FindAssets`, `EditorWindow`) and the `Inventories` namespace from [[Inventory Systems]]. Not compiled. ## 2.1 Folder and assemblies ```text Assets/Crafting/ Scripts/Runtime/ Crafting.Runtime.asmdef (references the Inventory assembly, Unity.InputSystem) Scripts/Editor/ Crafting.Editor.asmdef (Editor only, references Crafting.Runtime) Recipes/ RecipeDefinition assets Stations/ CraftingStationType assets UI/ CraftingView.uxml, Crafting.uss ``` If the inventory scripts have no assembly definition, either add one (`Inventories.Runtime`) or skip assembly definitions for crafting too; an asmdef cannot reference code in `Assembly-CSharp`. ## 2.2 `CraftingStationType` ```csharp using UnityEngine; namespace Crafting { /// <summary>A kind of station (Campfire, Workbench). Type Object; scenes hold CraftingStation instances. NOT compiled.</summary> [CreateAssetMenu(menuName = "Crafting/Station Type", fileName = "Station_")] public sealed class CraftingStationType : ScriptableObject { public string id; public string displayName; public Sprite icon; [Tooltip("Max queued jobs at one station of this type.")] [Min(1)] public int queueCapacity = 3; [Tooltip("Output slots where finished items wait.")] [Min(1)] public int outputSlots = 4; void OnValidate() { if (string.IsNullOrWhiteSpace(id)) id = name.ToLowerInvariant().Replace(' ', '_'); } } } ``` ## 2.3 `RecipeDefinition` ```csharp using System; using System.Collections.Generic; using Inventories; using UnityEngine; namespace Crafting { [Serializable] public struct Ingredient { public ItemDefinition item; [Min(1)] public int count; [Tooltip("False = a tool: required but not consumed (e.g. Hammer).")] public bool consumed; public Ingredient(ItemDefinition item, int count, bool consumed = true) { this.item = item; this.count = count; this.consumed = consumed; } } [Serializable] public struct RecipeOutput { public ItemDefinition item; [Min(1)] public int count; } /// <summary> /// One recipe. Inputs may include tools (not consumed). Station null = craft by hand. /// Saved and referenced by id, never by asset name. NOT compiled in Unity. /// </summary> [CreateAssetMenu(menuName = "Crafting/Recipe", fileName = "Recipe_")] public sealed class RecipeDefinition : ScriptableObject { [Tooltip("Stable id for saves. Never change after shipping.")] public string id; public string displayName; [TextArea] public string description; [Tooltip("Optional; defaults to the first output's icon.")] public Sprite iconOverride; public string category = "General"; public List<Ingredient> inputs = new(); public List<RecipeOutput> outputs = new(); [Header("Where and how long")] [Tooltip("None = by hand, anywhere.")] public CraftingStationType station; [Tooltip("0 = instant. Only stations can run timed recipes.")] [Min(0f)] public float craftSeconds; [Header("Discovery")] public bool unlockedByDefault; [Tooltip("Learn this recipe the first time the player picks up any consumed input.")] public bool discoverOnIngredientPickup = true; [Tooltip("Show as ??? in the list while unknown (instead of hiding it).")] public bool showWhenLocked; public Sprite Icon => iconOverride ? iconOverride : outputs.Count > 0 && outputs[0].item ? outputs[0].item.icon : null; public string DisplayName => string.IsNullOrEmpty(displayName) ? (outputs.Count > 0 && outputs[0].item ? outputs[0].item.displayName : name) : displayName; public bool IsTimed => craftSeconds > 0f; public bool ByHand => station == null; /// <summary>Returns human-readable problems; empty list = valid.</summary> public List<string> Validate() { var problems = new List<string>(); if (string.IsNullOrWhiteSpace(id)) problems.Add("missing id"); if (outputs.Count == 0) problems.Add("no outputs"); for (int i = 0; i < inputs.Count; i++) { if (!inputs[i].item) problems.Add(quot;input {i} has no item"); else if (inputs[i].count < 1) problems.Add(quot;input {i} count < 1"); for (int j = 0; j < i; j++) if (inputs[j].item && inputs[j].item == inputs[i].item) problems.Add(quot;input {i} duplicates input {j} ({inputs[i].item.id}); merge them"); } for (int i = 0; i < outputs.Count; i++) if (!outputs[i].item) problems.Add(quot;output {i} has no item"); if (IsTimed && ByHand) problems.Add("timed recipes need a station"); foreach (var input in inputs) foreach (var output in outputs) if (input.item && input.item == output.item && input.consumed) problems.Add(quot;{input.item.id} is both consumed and produced"); return problems; } void OnValidate() { if (string.IsNullOrWhiteSpace(id)) id = name.ToLowerInvariant().Replace(' ', '_'); for (int i = 0; i < inputs.Count; i++) { // New list entries default to consumed = false; most inputs are consumed. var x = inputs[i]; if (x.count < 1) { x.count = 1; x.consumed = true; inputs[i] = x; } } foreach (string p in Validate()) Debug.LogWarning(quot;[Recipe {name}] {p}", this); } } } ``` **Design notes** - **Tools** (`consumed = false`) are required but stay in the bag. A Hammer for nails is far more readable than a hidden "workbench tier". - **Duplicate inputs are rejected.** Two rows of "Stick x2" would make have/need counts wrong in the UI; merge them. - **Ids, not names.** Saves and knowledge store `id`. Renaming an asset must not break a save (the same rule as `ItemDefinition.id`). - **No recipe produces a consumed input.** Otherwise the "max craftable" loop in part 3 can run forever. ## 2.4 `RecipeBook` ```csharp using System.Collections.Generic; using Inventories; using UnityEngine; namespace Crafting { /// <summary>All recipes in the game. Lazy id cache like ItemDatabase. NOT compiled in Unity.</summary> [CreateAssetMenu(menuName = "Crafting/Recipe Book", fileName = "RecipeBook")] public sealed class RecipeBook : ScriptableObject { public List<RecipeDefinition> recipes = new(); Dictionary<string, RecipeDefinition> _byId; Dictionary<ItemDefinition, List<RecipeDefinition>> _byInput; public RecipeDefinition Get(string id) { if (string.IsNullOrEmpty(id)) return null; if (_byId == null) Rebuild(); _byId.TryGetValue(id, out var r); return r; } /// <summary>Recipes that consume this item (for ingredient discovery and "uses" tooltips).</summary> public IReadOnlyList<RecipeDefinition> UsingInput(ItemDefinition item) { if (_byInput == null) Rebuild(); return item != null && _byInput.TryGetValue(item, out var list) ? list : (IReadOnlyList<RecipeDefinition>)System.Array.Empty<RecipeDefinition>(); } /// <summary>Recipes craftable at this station type (null = by hand). Fills 'into' to avoid allocations.</summary> public void ForStation(CraftingStationType station, List<RecipeDefinition> into) { into.Clear(); foreach (var r in recipes) if (r && r.station == station) into.Add(r); } void Rebuild() { _byId = new Dictionary<string, RecipeDefinition>(recipes.Count); _byInput = new Dictionary<ItemDefinition, List<RecipeDefinition>>(); foreach (var r in recipes) { if (!r || string.IsNullOrEmpty(r.id)) continue; if (!_byId.TryAdd(r.id, r)) Debug.LogError(quot;[RecipeBook] Duplicate recipe id '{r.id}' ({r.name} vs {_byId[r.id].name})", this); foreach (var input in r.inputs) { if (!input.item || !input.consumed) continue; if (!_byInput.TryGetValue(input.item, out var list)) _byInput[input.item] = list = new List<RecipeDefinition>(); list.Add(r); } } } void OnValidate() { _byId = null; _byInput = null; } } } ``` ## 2.5 Editor audit window A recipe list grows quickly; catch mistakes before playtesters do. ```csharp #if UNITY_EDITOR using System.Collections.Generic; using System.Linq; using Inventories; using UnityEditor; using UnityEngine; namespace Crafting.EditorTools { /// <summary> /// Window > Crafting > Recipe Audit: lists invalid recipes, recipes missing from the book, /// items that nothing produces or uses, and simple production cycles. NOT compiled in Unity. /// </summary> public sealed class RecipeAuditWindow : EditorWindow { RecipeBook _book; Vector2 _scroll; readonly List<string> _report = new(); [MenuItem("Window/Crafting/Recipe Audit")] static void Open() => GetWindow<RecipeAuditWindow>("Recipe Audit"); void OnGUI() { _book = (RecipeBook)EditorGUILayout.ObjectField("Recipe Book", _book, typeof(RecipeBook), false); if (GUILayout.Button("Run audit")) Run(); _scroll = EditorGUILayout.BeginScrollView(_scroll); foreach (string line in _report) EditorGUILayout.LabelField(line, EditorStyles.wordWrappedLabel); EditorGUILayout.EndScrollView(); } void Run() { _report.Clear(); var all = AssetDatabase.FindAssets("t:RecipeDefinition") .Select(g => AssetDatabase.LoadAssetAtPath<RecipeDefinition>(AssetDatabase.GUIDToAssetPath(g))) .Where(r => r != null).ToList(); foreach (var r in all) foreach (string p in r.Validate()) _report.Add(quot;INVALID {r.name}: {p}"); if (_book) foreach (var r in all.Where(r => !_book.recipes.Contains(r))) _report.Add(quot;NOT IN BOOK: {r.name}"); var produced = new HashSet<ItemDefinition>(all.SelectMany(r => r.outputs).Select(o => o.item).Where(i => i)); var used = new HashSet<ItemDefinition>(all.SelectMany(r => r.inputs).Select(i => i.item).Where(i => i)); foreach (var item in produced.Where(i => !used.Contains(i) && i.useEffects.Count == 0 && !i.questItem)) _report.Add(quot;DEAD END? {item.id} is crafted but never used, has no use effects and is not a quest item"); // Cycle check: A -> B -> A through consumed inputs (depth-first over item graph). var edges = new Dictionary<ItemDefinition, List<ItemDefinition>>(); foreach (var r in all) foreach (var i in r.inputs.Where(i => i.item && i.consumed)) foreach (var o in r.outputs.Where(o => o.item)) { if (!edges.TryGetValue(i.item, out var list)) edges[i.item] = list = new List<ItemDefinition>(); list.Add(o.item); } var visiting = new HashSet<ItemDefinition>(); var done = new HashSet<ItemDefinition>(); foreach (var start in edges.Keys) Visit(start, edges, visiting, done); if (_report.Count == 0) _report.Add("No problems found."); } void Visit(ItemDefinition n, Dictionary<ItemDefinition, List<ItemDefinition>> edges, HashSet<ItemDefinition> visiting, HashSet<ItemDefinition> done) { if (done.Contains(n)) return; if (!visiting.Add(n)) { _report.Add(quot;CYCLE through {n.id} (check for infinite crafting loops)"); return; } if (edges.TryGetValue(n, out var next)) foreach (var m in next) Visit(m, edges, visiting, done); visiting.Remove(n); done.Add(n); } } } #endif ``` Cycles are not always bugs (Iron Ingot <-> Iron Scrap via smelting and salvaging), but each one deserves a look: if the loop *gains* items, players will find it. Custom Editor work is covered in [[Custom Inspectors and Editor Tooling]] and [[Editor Windows with UI Toolkit]]. ## 2.6 Steps 1. Create station types `Station_Campfire`, `Station_Workbench`. 2. Create items (from [[Inventory Systems]]): Stick, Stone, Cloth, Resin, Torch, Bandage, Raw Meat, Cooked Meat, Plank, Nails, Iron Scrap, Hammer, Tarp, Campfire Kit. 3. Create recipes (values used in part 6): | Recipe | Inputs | Output | Station | Time | Start known | |---|---|---|---|---|---| | Torch | Stick x1, Resin x1 | Torch x1 | hand | 0 | yes | | Bandage | Cloth x2 | Bandage x1 | hand | 0 | yes | | Campfire Kit | Stick x4, Stone x5 | Campfire Kit x1 | hand | 0 | yes | | Cooked Meat | Raw Meat x1 | Cooked Meat x1 | Campfire | 8 | yes | | Plank | Stick x3 | Plank x1 | Workbench | 4 | no (ingredient) | | Nails | Iron Scrap x1, Hammer (tool) | Nails x5 | Workbench | 6 | no (blueprint) | | Tarp | Cloth x3, Plank x2, Nails x4 | Tarp x1 | Workbench | 12 | no (blueprint) | 4. Create a `RecipeBook` and add every recipe; run *Window > Crafting > Recipe Audit*. ## Sources - `ScriptableObject` / `CreateAssetMenu`: https://docs.unity3d.com/6000.5/Documentation/ScriptReference/CreateAssetMenuAttribute.html - `MonoBehaviour.OnValidate`: https://docs.unity3d.com/6000.5/Documentation/ScriptReference/MonoBehaviour.OnValidate.html - `AssetDatabase.FindAssets`: https://docs.unity3d.com/6000.5/Documentation/ScriptReference/AssetDatabase.FindAssets.html - `EditorWindow.GetWindow`: https://docs.unity3d.com/6000.5/Documentation/ScriptReference/EditorWindow.GetWindow.html - [[Inventory Systems]], [[ScriptableObject Architecture]]