# 3. Crafting Service and Inventory Transactions Part of [[Crafting System]]. Prev: [[2. Recipe Assets and Recipe Book]]. Next: [[4. Crafting UI with UI Toolkit]]. > [!warning] Code not compiled > Written against the `Inventories` API from [[Inventory Systems]] (`Inventory(int capacity, float maxWeight)`, `Capacity`, `MaxWeight`, indexer, `Count`, `Has`, `RoomFor`, `Add` returning leftover, `Remove` returning removed, `RemoveAt`, `Set`, `Changed`; `InventoryHolder.Inventory`; `WorldPickup.Configure`) and Unity 6000.5 / NUnit as used by the Unity Test Framework. Not compiled. ## 3.1 The problem: `Inventory` has no transactions Crafting must be **all or nothing**: remove the inputs and add the outputs, or change nothing. The existing `Inventory` has separate `Remove` and `Add` calls. If you remove inputs and then `Add` returns leftover (bag full, too heavy), you have destroyed the player's items. Checking `RoomFor(output)` first is not enough: removing inputs can **free** a slot (so a craft that looks impossible is possible) and an output can stack into a partial stack. The robust answer is to **simulate on a copy**: 1. Clone the inventory (same capacity, weight limit and slots). 2. Run remove-then-add on the clone. 3. Only if the clone ends with nothing missing and no leftover, run the same operations on the real inventory. Because `Inventory.Add` and `Remove` are deterministic, the real run produces the same result as the simulation. No events fire for a failed attempt, so the UI never flickers. ## 3.2 Results and context ```csharp using Inventories; namespace Crafting { public enum CraftFailure { None, Unknown, // recipe not learned WrongStation, // needs a different station (or a station at all) StationNotReady, // fire out, no fuel... MissingIngredients, NoRoom, // bag full or too heavy QueueFull, } /// <summary>Outcome of an evaluation or a craft, with a player-facing reason. NOT compiled.</summary> public readonly struct CraftCheck { public readonly CraftFailure Failure; public readonly string Reason; public bool Ok => Failure == CraftFailure.None; public CraftCheck(CraftFailure failure, string reason) { Failure = failure; Reason = reason; } public static readonly CraftCheck Success = new(CraftFailure.None, ""); } /// <summary>Who knows which recipes. Part 5 implements it with RecipeKnowledge.</summary> public interface IRecipeKnowledge { bool Knows(RecipeDefinition recipe); } /// <summary>Everything the service needs to know about where the player is crafting.</summary> public readonly struct CraftContext { public readonly CraftingStationType StationType; // null = by hand public readonly bool StationReady; public readonly string StationNotReadyReason; public readonly int QueueFree; public readonly IRecipeKnowledge Knowledge; // null = everything known public CraftContext(CraftingStationType stationType, bool stationReady, string notReadyReason, int queueFree, IRecipeKnowledge knowledge) { StationType = stationType; StationReady = stationReady; StationNotReadyReason = notReadyReason; QueueFree = queueFree; Knowledge = knowledge; } public static CraftContext ByHand(IRecipeKnowledge knowledge = null) => new(null, true, "", 0, knowledge); } } ``` ## 3.3 `CraftingService` ```csharp using System; using System.Collections.Generic; using Inventories; namespace Crafting { /// <summary> /// Pure crafting logic over an Inventory. No MonoBehaviour, no UI: unit-testable. /// NOT compiled in Unity. /// </summary> public static class CraftingService { public const int MaxBatch = 99; /// <summary>Can 'times' crafts of this recipe start now? Reasons in priority order (part 1.7).</summary> public static CraftCheck Evaluate(RecipeDefinition r, Inventory inv, in CraftContext ctx, int times = 1) { CraftCheck basic = EvaluateIgnoringRoom(r, inv, ctx, times); if (!basic.Ok) return basic; // Timed recipes deliver into the station's output slots, not the bag. if (!r.IsTimed && !Simulate(r, inv, times)) return new CraftCheck(CraftFailure.NoRoom, "Not enough room"); return CraftCheck.Success; } /// <summary>Every check except bag room (knowledge, station, queue, ingredients).</summary> public static CraftCheck EvaluateIgnoringRoom(RecipeDefinition r, Inventory inv, in CraftContext ctx, int times = 1) { if (r == null) return new CraftCheck(CraftFailure.Unknown, "No recipe"); if (ctx.Knowledge != null && !ctx.Knowledge.Knows(r)) return new CraftCheck(CraftFailure.Unknown, "Recipe not learned"); if (r.station != ctx.StationType) return new CraftCheck(CraftFailure.WrongStation, r.station ? quot;Needs a {r.station.displayName}" : "Craft this by hand"); if (r.station && !ctx.StationReady) return new CraftCheck(CraftFailure.StationNotReady, ctx.StationNotReadyReason); if (r.IsTimed && ctx.QueueFree <= 0) return new CraftCheck(CraftFailure.QueueFull, "Queue full"); foreach (Ingredient ing in r.inputs) { int need = Needed(ing, times); int have = inv.Count(ing.item); if (have < need) return new CraftCheck(CraftFailure.MissingIngredients, quot;Need {need} {ing.item.displayName} (have {have})"); } return CraftCheck.Success; } /// <summary>Consumed inputs scale with times; tools are needed once.</summary> public static int Needed(in Ingredient ing, int times) => ing.consumed ? ing.count * times : ing.count; /// <summary>Largest batch that would pass Evaluate (0 if none).</summary> public static int MaxCraftable(RecipeDefinition r, Inventory inv, in CraftContext ctx) { if (!EvaluateIgnoringRoom(r, inv, ctx, 1).Ok) return 0; int max = MaxBatch; foreach (Ingredient ing in r.inputs) if (ing.consumed) max = Math.Min(max, inv.Count(ing.item) / ing.count); if (r.IsTimed) return Math.Max(0, max); // Room is NOT monotonic in batch size: a bigger batch can empty an input slot and make // room that a smaller batch does not (see the tests). So scan down from the top. for (int n = max; n >= 1; n--) if (Simulate(r, inv, n)) return n; return 0; } /// <summary>Instant craft: all or nothing.</summary> public static CraftCheck TryCraftInstant(RecipeDefinition r, Inventory inv, in CraftContext ctx, int times = 1) { if (r.IsTimed) return new CraftCheck(CraftFailure.WrongStation, "Timed recipe: queue it at a station"); CraftCheck check = Evaluate(r, inv, ctx, times); if (!check.Ok) return check; if (!Apply(r, inv, times)) { // Should be impossible after a successful simulation; if it happens, Add/Remove changed. UnityEngine.Debug.LogError(quot;[Crafting] Real craft diverged from simulation for {r.id}. Inventory may be inconsistent."); return new CraftCheck(CraftFailure.NoRoom, "Craft failed"); } return CraftCheck.Success; } /// <summary>Removes consumed inputs for 'times' crafts (timed recipes, on enqueue). Caller has evaluated.</summary> public static void ConsumeInputs(RecipeDefinition r, Inventory inv, int times) { foreach (Ingredient ing in r.inputs) if (ing.consumed) inv.Remove(ing.item, ing.count * times); } /// <summary>Gives back consumed inputs; returns what did not fit so the caller can drop it.</summary> public static List<ItemStack> RefundInputs(RecipeDefinition r, Inventory inv, int times) { var leftovers = new List<ItemStack>(); foreach (Ingredient ing in r.inputs) { if (!ing.consumed) continue; int left = inv.Add(ing.item, ing.count * times); if (left > 0) leftovers.Add(new ItemStack(ing.item, left)); } return leftovers; } // ---------- simulation ---------- public static Inventory Clone(Inventory src) { var copy = new Inventory(src.Capacity, src.MaxWeight); for (int i = 0; i < src.Capacity; i++) if (!src[i].IsEmpty) copy.Set(i, src[i]); return copy; } static bool Simulate(RecipeDefinition r, Inventory inv, int times) => Apply(r, Clone(inv), times); /// <summary>Remove consumed inputs, then add outputs. False if anything was short or did not fit.</summary> static bool Apply(RecipeDefinition r, Inventory inv, int times) { foreach (Ingredient ing in r.inputs) { if (!ing.consumed) continue; int need = ing.count * times; if (inv.Remove(ing.item, need) < need) return false; } foreach (RecipeOutput o in r.outputs) if (inv.Add(o.item, o.count * times) > 0) return false; return true; } } } ``` **Why this order of checks?** Part 1.7: the UI shows the *first* reason, so the most fundamental one wins ("Needs a Workbench" is more useful than "Need 3 Stick" when you are at the wrong place). **Cost.** `Clone` copies at most `Capacity` structs, and `MaxCraftable` may simulate up to `MaxBatch` times. That is fine for the *selected* recipe when `Inventory.Changed` fires. Do not call it for every recipe every frame (see part 7). ## 3.4 Stations: queue, time, output slots, requirements ```csharp using System; using System.Collections.Generic; using Inventories; using UnityEngine; namespace Crafting { /// <summary>A condition a station needs (fuel, fire lit, daylight). Add as components on the station.</summary> public interface IStationRequirement { bool IsMet(out string reason); } /// <summary>One queued craft (Command): can be cancelled for a refund of unstarted units.</summary> [Serializable] public sealed class CraftJob { public RecipeDefinition recipe; public int unitsLeft; public float unitTimeLeft; public bool stalled; // finished a unit but output slots are full public float UnitProgress01 => recipe.craftSeconds <= 0f ? 1f : 1f - unitTimeLeft / recipe.craftSeconds; } /// <summary> /// A crafting station in the scene. Inputs are consumed on enqueue; outputs go to the station's own /// Output inventory and wait to be collected. NOT compiled in Unity. /// </summary> public sealed class CraftingStation : MonoBehaviour { [SerializeField] CraftingStationType type; [Tooltip("Where refunds that fit nowhere are dropped.")] [SerializeField] Vector3 dropOffset = new(0f, 0.5f, 1f); readonly List<CraftJob> _queue = new(); IStationRequirement[] _requirements; public CraftingStationType Type => type; public Inventory Output { get; private set; } public IReadOnlyList<CraftJob> Queue => _queue; public int QueueFree => type.queueCapacity - _queue.Count; public event Action QueueChanged; public event Action<CraftJob> JobProgress; public event Action<RecipeDefinition> UnitCompleted; void Awake() { Output = new Inventory(type.outputSlots); _requirements = GetComponents<IStationRequirement>(); } public bool IsReady(out string reason) { foreach (var req in _requirements) if (!req.IsMet(out reason)) return false; reason = ""; return true; } public CraftContext ContextFor(IRecipeKnowledge knowledge) { bool ready = IsReady(out string reason); return new CraftContext(type, ready, reason, QueueFree, knowledge); } /// <summary>Queue a timed recipe, or run an instant station recipe straight into the player's bag.</summary> public CraftCheck Craft(RecipeDefinition r, Inventory from, IRecipeKnowledge knowledge, int times = 1) { CraftContext ctx = ContextFor(knowledge); if (!r.IsTimed) return CraftingService.TryCraftInstant(r, from, ctx, times); CraftCheck check = CraftingService.Evaluate(r, from, ctx, times); if (!check.Ok) return check; CraftingService.ConsumeInputs(r, from, times); _queue.Add(new CraftJob { recipe = r, unitsLeft = times, unitTimeLeft = r.craftSeconds }); QueueChanged?.Invoke(); return CraftCheck.Success; } /// <summary>Cancel a job: unstarted units are refunded (Command undo). The unit in progress is refunded too.</summary> public void Cancel(int index, Inventory refundTo) { if (index < 0 || index >= _queue.Count) return; CraftJob job = _queue[index]; _queue.RemoveAt(index); foreach (ItemStack left in CraftingService.RefundInputs(job.recipe, refundTo, job.unitsLeft)) { int stillLeft = Output.Add(left.item, left.count); if (stillLeft > 0) DropInWorld(left.item, stillLeft); } QueueChanged?.Invoke(); } /// <summary>Move everything from the output slots into an inventory. Returns true if all moved.</summary> public bool CollectAll(Inventory into) { bool all = true; for (int i = 0; i < Output.Capacity; i++) { ItemStack s = Output[i]; if (s.IsEmpty) continue; int left = into.Add(s.item, s.count, s.durability); int moved = s.count - left; if (moved > 0) Output.RemoveAt(i, moved); if (left > 0) all = false; } return all; } void Update() { if (_queue.Count == 0) return; if (!IsReady(out _)) return; // paused while the fire is out, etc. CraftJob job = _queue[0]; if (!job.stalled) { job.unitTimeLeft -= Time.deltaTime; JobProgress?.Invoke(job); if (job.unitTimeLeft > 0f) return; } TryDeliver(job); } void TryDeliver(CraftJob job) { // All outputs of one unit must fit, or the job waits (stalled) - nothing is lost. Inventory sim = CraftingService.Clone(Output); foreach (RecipeOutput o in job.recipe.outputs) if (sim.Add(o.item, o.count) > 0) { job.stalled = true; JobProgress?.Invoke(job); return; } foreach (RecipeOutput o in job.recipe.outputs) Output.Add(o.item, o.count); job.stalled = false; job.unitsLeft--; UnitCompleted?.Invoke(job.recipe); if (job.unitsLeft <= 0) _queue.RemoveAt(0); else job.unitTimeLeft = job.recipe.craftSeconds; QueueChanged?.Invoke(); } void DropInWorld(ItemDefinition item, int count) { if (!item.worldPrefab) { Debug.LogWarning(quot;[CraftingStation] Lost {count} x {item.id}: no worldPrefab to drop.", this); return; } GameObject go = Instantiate(item.worldPrefab, transform.TransformPoint(dropOffset), Quaternion.identity); if (go.TryGetComponent(out WorldPickup pickup)) pickup.Configure(item, count, 1.5f); } /// <summary>For saves (part 5).</summary> public void RestoreJob(RecipeDefinition r, int unitsLeft, float unitTimeLeft) { _queue.Add(new CraftJob { recipe = r, unitsLeft = unitsLeft, unitTimeLeft = unitTimeLeft }); QueueChanged?.Invoke(); } } } ``` **Design decisions** - **Consume on enqueue.** The player cannot queue three planks, then use the sticks elsewhere. Cancel refunds. - **Outputs to the station.** Finished items wait in `Output` (like a furnace). A full backpack never loses a craft; a full output stalls the queue visibly ("Output full"). - **Requirements pause, not cancel.** If rain puts the campfire out, cooking pauses and resumes when relit. - **Real time.** Jobs use `Time.deltaTime`, so they pause with the game. To use in-game hours instead, scale by `TimeOfDayClock.HoursPerSecond` from [[1. Time of Day Clock and Profiles]]. ## 3.5 `PlayerCrafter`: the scene entry point ```csharp using System; using Inventories; using UnityEngine; namespace Crafting { /// <summary> /// The player's crafting facade: knows the bag, the knowledge and the station in range. /// UI talks only to this. NOT compiled in Unity. /// </summary> [RequireComponent(typeof(InventoryHolder))] public sealed class PlayerCrafter : MonoBehaviour { [SerializeField] RecipeBook book; [Tooltip("Optional; if null every recipe counts as known.")] [SerializeField] MonoBehaviour knowledgeComponent; // must implement IRecipeKnowledge InventoryHolder _holder; IRecipeKnowledge _knowledge; public RecipeBook Book => book; public Inventory Inventory => _holder.Inventory; public IRecipeKnowledge Knowledge => _knowledge; public CraftingStation CurrentStation { get; private set; } public event Action<CraftingStation> StationChanged; public event Action<RecipeDefinition, int> Crafted; // recipe, times (instant) or queued public event Action<RecipeDefinition, CraftCheck> CraftFailed; void Awake() { _holder = GetComponent<InventoryHolder>(); _knowledge = knowledgeComponent as IRecipeKnowledge; if (knowledgeComponent && _knowledge == null) Debug.LogError("knowledgeComponent does not implement IRecipeKnowledge", this); } public void EnterStation(CraftingStation s) { CurrentStation = s; StationChanged?.Invoke(s); } public void LeaveStation(CraftingStation s) { if (CurrentStation != s) return; CurrentStation = null; StationChanged?.Invoke(null); } public CraftContext Context => CurrentStation ? CurrentStation.ContextFor(_knowledge) : CraftContext.ByHand(_knowledge); public CraftCheck Evaluate(RecipeDefinition r, int times = 1) => CraftingService.Evaluate(r, Inventory, Context, times); public int MaxCraftable(RecipeDefinition r) => CraftingService.MaxCraftable(r, Inventory, Context); public CraftCheck Craft(RecipeDefinition r, int times = 1) { CraftCheck result = CurrentStation && r.station == CurrentStation.Type ? CurrentStation.Craft(r, Inventory, _knowledge, times) : CraftingService.TryCraftInstant(r, Inventory, Context, times); if (result.Ok) Crafted?.Invoke(r, times); else CraftFailed?.Invoke(r, result); return result; } } /// <summary>Trigger volume around a station: tells the player's crafter it is in range. NOT compiled.</summary> [RequireComponent(typeof(Collider))] public sealed class CraftingStationZone : MonoBehaviour { [SerializeField] CraftingStation station; void Reset() => GetComponent<Collider>().isTrigger = true; void OnTriggerEnter(Collider other) { if (other.TryGetComponent(out PlayerCrafter c)) c.EnterStation(station); } void OnTriggerExit(Collider other) { if (other.TryGetComponent(out PlayerCrafter c)) c.LeaveStation(station); } } } ``` If your project already has an interaction system (look-at prompts, "Press E"), call `EnterStation` from the interactable instead of a trigger; see [[Context-Sensitive Prompts and Onboarding]]. ## 3.6 EditMode tests Pure C# logic deserves tests ([[Unity Test Framework]]). Create an Edit Mode test assembly that references `Crafting.Runtime` and the inventory assembly. ```csharp using Crafting; using Inventories; using NUnit.Framework; using UnityEngine; public class CraftingServiceTests { ItemDefinition stick, stone, kit, hammer, nails, scrap; static ItemDefinition Item(string id, int maxStack = 20, float weight = 0f) { var d = ScriptableObject.CreateInstance<ItemDefinition>(); d.id = id; d.displayName = id; d.maxStack = maxStack; d.weight = weight; return d; } static RecipeDefinition Recipe(ItemDefinition output, int outCount, params Ingredient[] inputs) { var r = ScriptableObject.CreateInstance<RecipeDefinition>(); r.id = output.id; r.inputs.AddRange(inputs); r.outputs.Add(new RecipeOutput { item = output, count = outCount }); return r; } [SetUp] public void SetUp() { stick = Item("stick"); stone = Item("stone"); kit = Item("kit", 1); hammer = Item("hammer", 1); nails = Item("nails", 50); scrap = Item("scrap"); } [Test] public void Craft_RemovesInputsAndAddsOutput() { var inv = new Inventory(4); inv.Add(stick, 4); inv.Add(stone, 5); var r = Recipe(kit, 1, new Ingredient(stick, 4), new Ingredient(stone, 5)); Assert.IsTrue(CraftingService.TryCraftInstant(r, inv, CraftContext.ByHand()).Ok); Assert.AreEqual(0, inv.Count(stick)); Assert.AreEqual(0, inv.Count(stone)); Assert.AreEqual(1, inv.Count(kit)); } [Test] public void Craft_FullBag_ChangesNothing() { var inv = new Inventory(2); inv.Add(stick, 20); inv.Add(stone, 20); // both slots full stacks var r = Recipe(kit, 1, new Ingredient(stick, 1)); // removing 1 stick frees no slot CraftCheck c = CraftingService.TryCraftInstant(r, inv, CraftContext.ByHand()); Assert.AreEqual(CraftFailure.NoRoom, c.Failure); Assert.AreEqual(20, inv.Count(stick)); Assert.AreEqual(0, inv.Count(kit)); } [Test] public void Craft_UsesSlotFreedByInputs() { var inv = new Inventory(2); inv.Add(stick, 4); inv.Add(stone, 20); // no empty slot before crafting var r = Recipe(kit, 1, new Ingredient(stick, 4)); // consuming all sticks frees a slot Assert.IsTrue(CraftingService.TryCraftInstant(r, inv, CraftContext.ByHand()).Ok); Assert.AreEqual(1, inv.Count(kit)); } [Test] public void Tool_IsRequiredButNotConsumed() { var inv = new Inventory(4); inv.Add(scrap, 2); inv.Add(hammer, 1); var r = Recipe(nails, 5, new Ingredient(scrap, 1), new Ingredient(hammer, 1, consumed: false)); Assert.IsTrue(CraftingService.TryCraftInstant(r, inv, CraftContext.ByHand(), 2).Ok); Assert.AreEqual(1, inv.Count(hammer)); Assert.AreEqual(10, inv.Count(nails)); } [Test] public void MaxCraftable_LimitedByRoom() { var inv = new Inventory(3); inv.Add(stick, 10); // slot 0 var r = Recipe(kit, 1, new Ingredient(stick, 2)); // kit maxStack 1 // Ingredients allow 5. n=2: 6 sticks stay in slot 0, kits fill slots 1-2 -> fits. // n=3: one kit too many. n=5: slot 0 empties but 5 kits need 5 slots -> no. Assert.AreEqual(2, CraftingService.MaxCraftable(r, inv, CraftContext.ByHand())); } [Test] public void MaxCraftable_BiggerBatchCanFitWhenSmallerDoesNot() { var pair = Item("pair", 2); // stacks to 2 var inv = new Inventory(1); inv.Add(stick, 4); // the only slot var r = Recipe(pair, 1, new Ingredient(stick, 2)); // n=1: 2 sticks remain, no slot for the output -> NoRoom. // n=2: all sticks used, slot frees, 2 outputs stack in it -> fits. Assert.AreEqual(CraftFailure.NoRoom, CraftingService.Evaluate(r, inv, CraftContext.ByHand(), 1).Failure); Assert.AreEqual(2, CraftingService.MaxCraftable(r, inv, CraftContext.ByHand())); } [Test] public void WrongStation_ReportsStation() { var inv = new Inventory(4); inv.Add(stick, 3); var bench = ScriptableObject.CreateInstance<CraftingStationType>(); bench.displayName = "Workbench"; var r = Recipe(kit, 1, new Ingredient(stick, 3)); r.station = bench; CraftCheck c = CraftingService.Evaluate(r, inv, CraftContext.ByHand()); Assert.AreEqual(CraftFailure.WrongStation, c.Failure); StringAssert.Contains("Workbench", c.Reason); } } ``` The second `MaxCraftable` test is the reason the service scans down instead of binary searching: room is not monotonic in batch size, because a larger batch can empty an input slot. The UI in part 4 therefore offers "Max" even when a single craft says *Not enough room*. ## Sources - [[Inventory Systems]] (the `Inventory` API and its EditMode tests) - [[Unity Test Framework]] - `Object.Instantiate`: https://docs.unity3d.com/6000.5/Documentation/ScriptReference/Object.Instantiate.html - `Component.TryGetComponent`: https://docs.unity3d.com/6000.5/Documentation/ScriptReference/Component.TryGetComponent.html - `MonoBehaviour.OnTriggerEnter`: https://docs.unity3d.com/6000.5/Documentation/ScriptReference/MonoBehaviour.OnTriggerEnter.html - [[Game Programming Patterns (Review)]] (Command, Prototype)