quot;[RecipeKnowledge] Unknown recipe id '{id}' in save, skipped."); } } // Ingredient discovery: the first time an item is in the bag, learn recipes that use it. void ScanForNewIngredients() { Inventory inv = holder.Inventory; for (int i = 0; i < inv.Capacity; i++) { ItemStack s = inv[i]; if (s.IsEmpty || !_seenItems.Add(s.item)) continue; foreach (RecipeDefinition r in book.UsingInput(s.item)) if (r.discoverOnIngredientPickup) Learn(r); } } } } ``` **Discovery and re-entrancy.** `ScanForNewIngredients` runs inside `Inventory.Changed`. It only *reads* the inventory and raises `Learned`; listeners (the UI, a toast) must not modify the inventory in that handler. [[Inventory Systems]] warns about the same re-entrancy. **Should seen items be saved?** No: on load, `ScanForNewIngredients` runs again over the restored bag, and learning an already-known recipe is a no-op (`HashSet.Add` returns false), so no duplicate toasts. ## 5.2 Blueprints: `LearnRecipeEffect` Blueprints are ordinary items from [[Inventory Systems]] (`consumable = true`) with this effect in `useEffects`. Using one teaches the recipe and consumes the blueprint; if the recipe is already known, `Apply` returns false and `InventoryHolder.Use` keeps the item. ```csharp using Inventories; using UnityEngine; namespace Crafting { /// <summary>ItemEffect for blueprint items: teaches a recipe. NOT compiled in Unity.</summary> [CreateAssetMenu(menuName = "Crafting/Effects/Learn Recipe", fileName = "Effect_LearnRecipe_")] public sealed class LearnRecipeEffect : ItemEffect { public RecipeDefinition recipe; public override bool Apply(GameObject user) { RecipeKnowledge knowledge = user.GetComponentInParent<RecipeKnowledge>(); if (!knowledge) { Debug.LogWarning(quot;[LearnRecipeEffect] {user.name} has no RecipeKnowledge.", user); return false; } return knowledge.Learn(recipe); // false = already known: blueprint is not consumed } } } ``` **Steps** 1. *Create > Crafting > Effects > Learn Recipe*: `Effect_LearnRecipe_Tarp`, recipe `Tarp`. 2. Item `Blueprint: Tarp`: category Collectible, consumable, maxStack 1, `useEffects` = the effect, a paper icon, a world prefab with `WorldPickup`. 3. Place it where Level Up! says rewards go: at the end of a small optional challenge, visible before reachable. ## 5.3 Other ways to learn | Source | Call | |---|---| | Quest reward | `RecipeKnowledge.Learn("tarp")` from the reward step ([[Quest Systems]]) | | NPC teaches | dialogue action calls `Learn` ([[0.Dialogue System]]) | | Achievement / unlock flag | when a flag from [[5. Unlocks Achievements and Progress Saves]] is set, learn the matching recipe | | Level start | `unlockedByDefault` on the asset | Keep **one** owner of the knowledge set (this component). Other systems ask it; they do not keep their own "known recipes" list. ## 5.4 Discovery toast ```csharp using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UIElements; namespace Crafting { /// <summary>"New recipe: Tarp" toast on a PanelRenderer (6000.5). NOT compiled in Unity.</summary> [RequireComponent(typeof(PanelRenderer))] public sealed class RecipeToast : MonoBehaviour { [SerializeField] RecipeKnowledge knowledge; [SerializeField] float seconds = 2.5f; Label _label; readonly Queue<string> _pending = new(); bool _showing; PanelRenderer _panelRenderer; int _loadedVersion = -1; void OnEnable() { knowledge.Learned += OnLearned; _panelRenderer = GetComponent<PanelRenderer>(); _panelRenderer.RegisterUIReloadCallback(OnUIReload); } void OnUIReload(PanelRenderer renderer, VisualElement root, int version) { if (version == _loadedVersion) return; // tree kept: label still attached _loadedVersion = version; _label = new Label(); _label.AddToClassList("recipe-toast"); _label.style.position = Position.Absolute; _label.style.top = Length.Percent(12); _label.style.alignSelf = Align.Center; _label.style.fontSize = 22; _label.style.display = DisplayStyle.None; root.Add(_label); } void OnDisable() { knowledge.Learned -= OnLearned; if (_panelRenderer) _panelRenderer.UnregisterUIReloadCallback(OnUIReload); _showing = false; // coroutines stop when the component is disabled } void OnLearned(RecipeDefinition r) { _pending.Enqueue(quot;New recipe: {r.DisplayName}"); if (!_showing && _label != null) StartCoroutine(Show()); } IEnumerator Show() { _showing = true; while (_pending.Count > 0) { _label.text = _pending.Dequeue(); _label.style.display = DisplayStyle.Flex; yield return new WaitForSeconds(seconds); _label.style.display = DisplayStyle.None; yield return new WaitForSeconds(0.2f); } _showing = false; } } } ``` Queuing matters: picking up a new ingredient can teach two recipes at once, and both deserve a moment. ## 5.5 Saving: knowledge, queues and outputs The bag itself is already saved by `InventorySaveController` ([[Inventory Systems]] section 7). Crafting adds three things: ```csharp using System; using System.Collections.Generic; using System.IO; using Inventories; using UnityEngine; namespace Crafting { /// <summary> /// Saves known recipe ids, station queues and station output slots as one JSON file. /// Stations are identified by a designer-set id in this component, not by scene object names. /// NOT compiled in Unity. /// </summary> public sealed class CraftingSaveController : MonoBehaviour { [Serializable] public struct StationEntry { public string id; // "village_workbench" - stable, unique per scene public CraftingStation station; } [Serializable] sealed class SaveData { public int version = 1; public List<string> knownRecipes = new(); public List<StationData> stations = new(); } [Serializable] sealed class StationData { public string id; public List<JobData> jobs = new(); public InventorySave output; } [Serializable] struct JobData { public string recipeId; public int unitsLeft; public float unitTimeLeft; } [SerializeField] RecipeKnowledge knowledge; [SerializeField] RecipeBook book; [SerializeField] ItemDatabase items; [SerializeField] List<StationEntry> stations = new(); [SerializeField] string fileName = "crafting.json"; string PathOnDisk => Path.Combine(Application.persistentDataPath, fileName); void Start() => Load(); void OnApplicationQuit() => Save(); public void Save() { var data = new SaveData(); data.knownRecipes.AddRange(knowledge.KnownIds); foreach (StationEntry e in stations) { if (!e.station) continue; var sd = new StationData { id = e.id, output = InventorySave.Capture(e.station.Output) }; foreach (CraftJob job in e.station.Queue) sd.jobs.Add(new JobData { recipeId = job.recipe.id, unitsLeft = job.unitsLeft, unitTimeLeft = job.unitTimeLeft }); data.stations.Add(sd); } string tmp = PathOnDisk + ".tmp"; File.WriteAllText(tmp, JsonUtility.ToJson(data, true)); if (File.Exists(PathOnDisk)) File.Replace(tmp, PathOnDisk, null); else File.Move(tmp, PathOnDisk); } public void Load() { if (!File.Exists(PathOnDisk)) return; SaveData data; try { data = JsonUtility.FromJson<SaveData>(File.ReadAllText(PathOnDisk)); } catch (Exception ex) { Debug.LogWarning(quot;[CraftingSave] Unreadable save, ignoring: {ex.Message}"); return; } if (data == null) return; knowledge.Restore(data.knownRecipes); foreach (StationData sd in data.stations) { CraftingStation station = stations.Find(e => e.id == sd.id).station; if (!station) { Debug.LogWarning(quot;[CraftingSave] No station with id '{sd.id}' in this scene."); continue; } sd.output?.Restore(station.Output, items); foreach (JobData j in sd.jobs) { RecipeDefinition r = book.Get(j.recipeId); if (r) station.RestoreJob(r, j.unitsLeft, j.unitTimeLeft); } } } } } ``` **Notes** - **Ids everywhere.** Recipes and items by `id`, stations by a designer-set id. Never save asset names or instance IDs (`JsonUtility` would write Unity object references as instance IDs that are only valid in the same session, as [[Inventory Systems]] notes). - **Load order.** `CraftingStation.Awake` creates `Output`; `RecipeKnowledge.Awake` adds the defaults; this controller loads in `Start`, after both. - **Versioning.** Bump `version` when the format changes and migrate in `Load`. - **One save system.** If the project has a central save ([[High Scores, Saves and Player Stats]], [[3. Player Data Save and Load]]), move `SaveData` into it instead of writing a separate file. ## Sources - `JsonUtility.ToJson` / `FromJson`: https://docs.unity3d.com/6000.5/Documentation/ScriptReference/JsonUtility.html - `Application.persistentDataPath`: https://docs.unity3d.com/6000.5/Documentation/ScriptReference/Application-persistentDataPath.html - `Component.GetComponentInParent`: https://docs.unity3d.com/6000.5/Documentation/ScriptReference/Component.GetComponentInParent.html - `PanelRenderer.RegisterUIReloadCallback` (6000.5): https://docs.unity3d.com/6000.5/Documentation/ScriptReference/UIElements.PanelRenderer.RegisterUIReloadCallback.html - `Length.Percent`: https://docs.unity3d.com/6000.5/Documentation/ScriptReference/UIElements.Length.Percent.html - [[Inventory Systems]], [[Power-Ups, Pickups and Unlockables]], [[Quest Systems]], [[Level Up! (Review)]]