# 4. Crafting UI with UI Toolkit Part of [[Crafting System]]. Prev: [[3. Crafting Service and Inventory Transactions]]. Next: [[5. Recipe Discovery Unlocks and Saves]]. > [!warning] Code not compiled > Written against the Unity 6000.5 UI Toolkit API (`PanelRenderer.RegisterUIReloadCallback`, `ListView.makeItem`/`bindItem`/`itemsSource`/`selectionChanged`/`RefreshItems`/`Rebuild`, `ProgressBar`, `Image.sprite`, `Button.clicked`, `VisualElement.SetEnabled`/`EnableInClassList`, `Focusable.Focus`) and Input System 1.20 (`InputActionReference`, `InputAction.WasPressedThisFrame`). Not compiled. UI Toolkit runtime basics (Panel Settings, the 6000.5 `PanelRenderer` and its reload-callback pattern, USS) are in [[2.UI Toolkit Project Setup]]; a ListView inventory is in [[3.HUD and Inventory Example]]. This part reuses those ideas and focuses on crafting. ## 4.1 Layout ```text ┌ Crafting - Workbench ────────────────────────────────────── [X] ┐ │ ┌ Recipes ───────────┐ ┌ Detail ──────────────────────────────┐ │ │ │ [icon] Plank ● │ │ [ICON] Tarp │ │ │ │ [icon] Nails │ │ Keeps rain off whatever is under it. │ │ │ │ [icon] Tarp ● │ │ Requires │ │ │ │ [icon] ??? │ │ [i] Cloth 3 / 3 │ │ │ └────────────────────┘ │ [i] Plank 1 / 2 (red) │ │ │ │ [i] Nails 4 / 4 │ │ │ │ Time 12 s [-] 1 [+] [Max] │ │ │ │ Need 2 Plank (have 1) │ │ │ │ [ Craft ] │ │ │ └──────────────────────────────────────┘ │ │ Queue: Plank x2 [██████░░░░] [Cancel] Output: [Plank 1] [Collect all] │ └──────────────────────────────────────────────────────────────────┘ ``` ## 4.2 `CraftingView.uxml` ```xml <ui:UXML xmlns:ui="UnityEngine.UIElements"> <Style src="Crafting.uss" /> <ui:VisualElement name="crafting-root" class="crafting"> <ui:VisualElement class="crafting__header"> <ui:Label name="station-title" text="Crafting" class="crafting__title" /> <ui:Button name="close-button" text="X" class="crafting__close" /> </ui:VisualElement> <ui:VisualElement class="crafting__body"> <ui:ListView name="recipe-list" class="crafting__list" /> <ui:VisualElement name="detail" class="crafting__detail"> <ui:VisualElement class="crafting__detail-head"> <ui:Image name="detail-icon" class="crafting__icon" /> <ui:Label name="detail-name" class="crafting__name" /> </ui:VisualElement> <ui:Label name="detail-desc" class="crafting__desc" /> <ui:Label text="Requires" class="crafting__section" /> <ui:VisualElement name="ingredients" class="crafting__ingredients" /> <ui:VisualElement class="crafting__amount-row"> <ui:Label name="detail-time" class="crafting__time" /> <ui:Button name="minus-button" text="-" class="crafting__small" /> <ui:Label name="amount" text="1" class="crafting__amount" /> <ui:Button name="plus-button" text="+" class="crafting__small" /> <ui:Button name="max-button" text="Max" class="crafting__small" /> </ui:VisualElement> <ui:Label name="reason" class="crafting__reason" /> <ui:Button name="craft-button" text="Craft" class="crafting__craft" /> </ui:VisualElement> </ui:VisualElement> <ui:VisualElement name="station-panel" class="crafting__station"> <ui:VisualElement class="crafting__station-col"> <ui:Label text="Queue" class="crafting__section" /> <ui:VisualElement name="queue" /> </ui:VisualElement> <ui:VisualElement class="crafting__station-col"> <ui:Label text="Output" class="crafting__section" /> <ui:VisualElement name="output" class="crafting__output" /> <ui:Button name="collect-button" text="Collect all" /> </ui:VisualElement> </ui:VisualElement> </ui:VisualElement> </ui:UXML> ``` ## 4.3 `Crafting.uss` ```css .crafting { position: absolute; left: 10%; right: 10%; top: 10%; bottom: 10%; background-color: rgba(20, 22, 28, 0.94); border-radius: 8px; padding: 12px; color: rgb(230, 230, 230); } .crafting--hidden { display: none; } .crafting__header { flex-direction: row; justify-content: space-between; margin-bottom: 8px; } .crafting__title { font-size: 22px; -unity-font-style: bold; } .crafting__body { flex-direction: row; flex-grow: 1; } .crafting__list { width: 38%; min-width: 220px; margin-right: 12px; } .crafting__detail { flex-grow: 1; } .crafting__detail-head { flex-direction: row; align-items: center; } .crafting__icon { width: 64px; height: 64px; margin-right: 8px; } .crafting__name { font-size: 20px; -unity-font-style: bold; } .crafting__desc { white-space: normal; margin: 6px 0; color: rgb(190, 190, 190); } .crafting__section { margin-top: 8px; -unity-font-style: bold; color: rgb(160, 200, 255); } .recipe-row { flex-direction: row; align-items: center; height: 40px; padding: 0 6px; } .recipe-row__icon { width: 32px; height: 32px; margin-right: 8px; } .recipe-row__name { flex-grow: 1; } .recipe-row__badge { width: 10px; height: 10px; border-radius: 5px; background-color: rgba(0, 0, 0, 0); } .recipe-row--craftable .recipe-row__badge { background-color: rgb(90, 200, 110); } .recipe-row--locked .recipe-row__name { color: rgb(120, 120, 120); -unity-font-style: italic; } .ingredient { flex-direction: row; align-items: center; height: 28px; } .ingredient__icon { width: 24px; height: 24px; margin-right: 6px; } .ingredient__name { flex-grow: 1; } .ingredient__count { min-width: 70px; -unity-text-align: middle-right; } .ingredient--missing .ingredient__count { color: rgb(255, 110, 100); } .ingredient--tool .ingredient__name { -unity-font-style: italic; } .crafting__amount-row { flex-direction: row; align-items: center; margin-top: 8px; } .crafting__time { flex-grow: 1; } .crafting__small { min-width: 36px; } .crafting__amount { min-width: 32px; -unity-text-align: middle-center; } .crafting__reason { color: rgb(255, 170, 90); min-height: 20px; margin-top: 6px; } .crafting__craft { height: 44px; font-size: 18px; margin-top: 6px; } .crafting__station { flex-direction: row; border-top-width: 1px; border-top-color: rgb(60, 60, 70); margin-top: 8px; padding-top: 6px; } .crafting__station-col { flex-grow: 1; } .queue-row { flex-direction: row; align-items: center; } .queue-row__bar { flex-grow: 1; margin: 0 6px; } .queue-row--stalled .queue-row__bar { opacity: 0.6; } .crafting__output { flex-direction: row; } .output-slot { width: 48px; height: 48px; margin-right: 4px; background-color: rgba(255, 255, 255, 0.06); } .output-slot__count { position: absolute; right: 2px; bottom: 0; font-size: 12px; } ``` Colour is not the only signal (accessibility): missing ingredients also show `have / need` numbers, and the reason line says what is wrong ([[Accessibility]]). ## 4.4 `CraftingView` ```csharp using System.Collections.Generic; using System.Linq; using Inventories; using UnityEngine; using UnityEngine.InputSystem; using UnityEngine.UIElements; namespace Crafting { /// <summary> /// Runtime crafting screen. Talks only to PlayerCrafter (and the current station's events). /// Refreshes on events, never every frame (except progress bars). NOT compiled in Unity. /// </summary> [RequireComponent(typeof(PanelRenderer))] public sealed class CraftingView : MonoBehaviour { [SerializeField] PlayerCrafter crafter; [SerializeField] InputActionReference toggleAction; // e.g. "UI/ToggleCrafting" bound to C / gamepad View [SerializeField] InputActionReference cancelAction; // e.g. "UI/Cancel" [SerializeField] bool startHidden = true; VisualElement _root, _panel, _ingredients, _queue, _output, _stationPanel; ListView _list; Label _title, _name, _desc, _time, _amount, _reason; Image _icon; Button _craft, _minus, _plus, _max, _close, _collect; readonly List<RecipeDefinition> _all = new(); readonly List<RecipeDefinition> _visible = new(); readonly List<ProgressBar> _queueBars = new(); RecipeDefinition _selected; int _amountValue = 1; CraftingStation _boundStation; public bool IsOpen { get; private set; } // ---------- lifecycle ---------- PanelRenderer _panelRenderer; int _loadedVersion = -1; // Start (not OnEnable): PlayerCrafter and InventoryHolder create their state in Awake, // and Awake order across GameObjects is not guaranteed. void Start() { crafter.Inventory.Changed += OnInventoryChanged; crafter.StationChanged += OnStationChanged; if (crafter.Knowledge is RecipeKnowledge rk) rk.Learned += OnLearned; // part 5 toggleAction.action.Enable(); if (cancelAction) cancelAction.action.Enable(); // 6000.5 PanelRenderer has no rootVisualElement: register a reload callback. It runs now if // the UI is already loaded and again whenever the tree is rebuilt (2.UI Toolkit Project Setup). _panelRenderer = GetComponent<PanelRenderer>(); _panelRenderer.RegisterUIReloadCallback(OnUIReload); } void OnUIReload(PanelRenderer renderer, VisualElement root, int version) { if (version == _loadedVersion) return; // same tree: do not wire buttons twice _loadedVersion = version; _root = root; _panel = _root.Q<VisualElement>("crafting-root"); _list = _root.Q<ListView>("recipe-list"); _ingredients = _root.Q<VisualElement>("ingredients"); _queue = _root.Q<VisualElement>("queue"); _output = _root.Q<VisualElement>("output"); _stationPanel = _root.Q<VisualElement>("station-panel"); _title = _root.Q<Label>("station-title"); _name = _root.Q<Label>("detail-name"); _desc = _root.Q<Label>("detail-desc"); _time = _root.Q<Label>("detail-time"); _amount = _root.Q<Label>("amount"); _reason = _root.Q<Label>("reason"); _icon = _root.Q<Image>("detail-icon"); _craft = _root.Q<Button>("craft-button"); _minus = _root.Q<Button>("minus-button"); _plus = _root.Q<Button>("plus-button"); _max = _root.Q<Button>("max-button"); _close = _root.Q<Button>("close-button"); _collect = _root.Q<Button>("collect-button"); SetupList(); _craft.clicked += OnCraft; _minus.clicked += () => SetAmount(_amountValue - 1); _plus.clicked += () => SetAmount(_amountValue + 1); _max.clicked += () => SetAmount(_selected ? crafter.MaxCraftable(_selected) : 1); _close.clicked += Close; _collect.clicked += () => { if (_boundStation) _boundStation.CollectAll(crafter.Inventory); }; _boundStation = null; // re-bind station rows against the new tree if (IsOpen) Open(); else if (startHidden) Close(); else Open(); } void OnDestroy() { if (_panelRenderer) _panelRenderer.UnregisterUIReloadCallback(OnUIReload); if (crafter != null) { crafter.Inventory.Changed -= OnInventoryChanged; crafter.StationChanged -= OnStationChanged; if (crafter.Knowledge is RecipeKnowledge rk) rk.Learned -= OnLearned; } if (_panel != null) BindStation(null); } void Update() { if (_panel == null) return; // UI not loaded yet if (toggleAction.action.WasPressedThisFrame()) { if (IsOpen) Close(); else Open(); } if (IsOpen && cancelAction && cancelAction.action.WasPressedThisFrame()) Close(); } public void Open() { IsOpen = true; _panel.RemoveFromClassList("crafting--hidden"); BindStation(crafter.CurrentStation); RebuildRecipes(); _list.Focus(); // gamepad / keyboard navigation starts in the list UnityEngine.Cursor.lockState = CursorLockMode.None; UnityEngine.Cursor.visible = true; } public void Close() { IsOpen = false; _panel.AddToClassList("crafting--hidden"); BindStation(null); } // ---------- recipe list ---------- void SetupList() { _list.fixedItemHeight = 40; _list.selectionType = SelectionType.Single; _list.itemsSource = _visible; _list.makeItem = () => { var row = new VisualElement(); row.AddToClassList("recipe-row"); var icon = new Image { name = "icon" }; icon.AddToClassList("recipe-row__icon"); var label = new Label { name = "name" }; label.AddToClassList("recipe-row__name"); var badge = new VisualElement { name = "badge" }; badge.AddToClassList("recipe-row__badge"); row.Add(icon); row.Add(label); row.Add(badge); return row; }; _list.bindItem = (element, index) => { RecipeDefinition r = _visible[index]; bool known = crafter.Knowledge == null || crafter.Knowledge.Knows(r); element.Q<Image>("icon").sprite = known ? r.Icon : null; element.Q<Label>("name").text = known ? r.DisplayName : "???"; element.EnableInClassList("recipe-row--locked", !known); element.EnableInClassList("recipe-row--craftable", known && crafter.Evaluate(r).Ok); }; _list.selectionChanged += items => Select(items.FirstOrDefault() as RecipeDefinition); } void RebuildRecipes() { crafter.Book.ForStation(crafter.CurrentStation ? crafter.CurrentStation.Type : null, _all); _visible.Clear(); foreach (RecipeDefinition r in _all) { bool known = crafter.Knowledge == null || crafter.Knowledge.Knows(r); if (known || r.showWhenLocked) _visible.Add(r); } // Craftable first, then by category and name: the eye lands on what you can do now. _visible.Sort((a, b) => { int ca = crafter.Evaluate(a).Ok ? 0 : 1, cb = crafter.Evaluate(b).Ok ? 0 : 1; if (ca != cb) return ca.CompareTo(cb); int cat = string.CompareOrdinal(a.category, b.category); return cat != 0 ? cat : string.CompareOrdinal(a.DisplayName, b.DisplayName); }); _list.Rebuild(); _title.text = crafter.CurrentStation ? crafter.CurrentStation.Type.displayName : "Crafting (by hand)"; int keep = _selected ? _visible.IndexOf(_selected) : -1; if (keep < 0 && _visible.Count > 0) keep = 0; if (keep >= 0) { _list.SetSelection(keep); Select(_visible[keep]); // SetSelection may not raise selectionChanged if the index is unchanged } else Select(null); } // ---------- detail ---------- void Select(RecipeDefinition r) { _selected = r; _amountValue = 1; RefreshDetail(); } void SetAmount(int value) { _amountValue = Mathf.Clamp(value, 1, CraftingService.MaxBatch); RefreshDetail(); } void RefreshDetail() { _ingredients.Clear(); if (_selected == null) { _name.text = ""; _desc.text = ""; _time.text = ""; _reason.text = ""; _icon.sprite = null; _craft.SetEnabled(false); return; } bool known = crafter.Knowledge == null || crafter.Knowledge.Knows(_selected); _icon.sprite = known ? _selected.Icon : null; _name.text = known ? _selected.DisplayName : "Unknown recipe"; _desc.text = known ? _selected.description : "Find a blueprint or a new ingredient to learn this."; _time.text = _selected.IsTimed ? quot;Time {_selected.craftSeconds:0.#} s each" : "Instant"; _amount.text = _amountValue.ToString(); if (known) { foreach (Ingredient ing in _selected.inputs) _ingredients.Add(MakeIngredientRow(ing, _amountValue)); } CraftCheck check = crafter.Evaluate(_selected, _amountValue); _reason.text = check.Ok ? "" : check.Reason; _craft.text = _selected.IsTimed ? "Queue" : "Craft"; _craft.SetEnabled(check.Ok); } VisualElement MakeIngredientRow(Ingredient ing, int times) { int need = CraftingService.Needed(ing, times); int have = crafter.Inventory.Count(ing.item); var row = new VisualElement(); row.AddToClassList("ingredient"); row.EnableInClassList("ingredient--missing", have < need); row.EnableInClassList("ingredient--tool", !ing.consumed); var icon = new Image { sprite = ing.item.icon }; icon.AddToClassList("ingredient__icon"); var name = new Label(ing.consumed ? ing.item.displayName : quot;{ing.item.displayName} (tool)"); name.AddToClassList("ingredient__name"); var count = new Label(quot;{have} / {need}"); count.AddToClassList("ingredient__count"); row.Add(icon); row.Add(name); row.Add(count); return row; } void OnCraft() { if (_selected == null) return; CraftCheck result = crafter.Craft(_selected, _amountValue); if (!result.Ok) _reason.text = result.Reason; // Inventory.Changed / station events refresh the rest. } // ---------- station ---------- void BindStation(CraftingStation s) { if (_boundStation) { _boundStation.QueueChanged -= RebuildQueue; _boundStation.JobProgress -= OnJobProgress; _boundStation.Output.Changed -= RebuildOutput; } _boundStation = s; _stationPanel.style.display = s ? DisplayStyle.Flex : DisplayStyle.None; if (!s) return; s.QueueChanged += RebuildQueue; s.JobProgress += OnJobProgress; s.Output.Changed += RebuildOutput; RebuildQueue(); RebuildOutput(); } void RebuildQueue() { _queue.Clear(); _queueBars.Clear(); if (!_boundStation) return; IReadOnlyList<CraftJob> jobs = _boundStation.Queue; for (int i = 0; i < jobs.Count; i++) { int index = i; // capture for the lambda CraftJob job = jobs[i]; var row = new VisualElement(); row.AddToClassList("queue-row"); row.Add(new Label(quot;{job.recipe.DisplayName} x{job.unitsLeft}")); var bar = new ProgressBar { lowValue = 0f, highValue = 1f, value = i == 0 ? job.UnitProgress01 : 0f }; bar.AddToClassList("queue-row__bar"); row.Add(bar); _queueBars.Add(bar); var cancel = new Button(() => _boundStation.Cancel(index, crafter.Inventory)) { text = "Cancel" }; row.Add(cancel); _queue.Add(row); } RefreshDetail(); // queue space changed } void OnJobProgress(CraftJob job) { if (_queueBars.Count == 0) return; ProgressBar bar = _queueBars[0]; bar.value = job.UnitProgress01; bar.title = job.stalled ? "Output full" : ""; bar.parent.EnableInClassList("queue-row--stalled", job.stalled); } void RebuildOutput() { _output.Clear(); if (!_boundStation) return; Inventory output = _boundStation.Output; for (int i = 0; i < output.Capacity; i++) { ItemStack s = output[i]; var slot = new VisualElement(); slot.AddToClassList("output-slot"); if (!s.IsEmpty) { slot.Add(new Image { sprite = s.item.icon }); var count = new Label(s.count > 1 ? s.count.ToString() : ""); count.AddToClassList("output-slot__count"); slot.Add(count); } _output.Add(slot); } } // ---------- events ---------- void OnInventoryChanged() { if (!IsOpen) return; _list.RefreshItems(); // craftable badges RefreshDetail(); // have/need numbers } void OnStationChanged(CraftingStation s) { if (!IsOpen) return; BindStation(s); RebuildRecipes(); } void OnLearned(RecipeDefinition r) { if (IsOpen) RebuildRecipes(); } } } ``` ## 4.5 Wiring 1. *Create > UI Toolkit > UI Document* (the UXML asset) for `CraftingView.uxml`; *Create > UI Toolkit > Style Sheet* for `Crafting.uss`; paste the code above. 2. A `PanelSettings` asset with **Scale Mode: Scale With Screen Size** (reference 1920 x 1080). Reuse the game's panel settings if it has one. 3. A `CraftingUI` GameObject: *GameObject > UI Toolkit > Panel Renderer* (Source Asset `CraftingView.uxml`, the panel settings, a Sort Order above the HUD) and `CraftingView` (assign the player's `PlayerCrafter`). `UIDocument` (now under *UI Toolkit/Legacy* in the Add Component menu) still works; swap `GetComponent<PanelRenderer>()` + callback for `GetComponent<UIDocument>().rootVisualElement` if your project uses it. 4. Input actions (see [[Input System]]): in the *UI* map add `ToggleCrafting` (Keyboard C, Gamepad Select/View) and use the existing `Cancel`. Assign both `InputActionReference`s. When the screen opens, switch the player's action map to UI so movement and attack stop; switch back on close. 5. Test with mouse, then with a gamepad only: the list must take focus on open, arrows/stick move through recipes, Tab/shoulder moves to the craft button. > [!tip] Rebuild vs RefreshItems > `RebuildRecipes` changes **which** recipes are visible, so it calls `ListView.Rebuild()`. Inventory changes only change **how** rows look, so they call `RefreshItems()`. Detail rows are rebuilt because there are only a handful. See [[7.UI Toolkit Pitfalls and Performance]]. ## Sources - `ListView` (`makeItem`, `bindItem`, `fixedItemHeight`): https://docs.unity3d.com/6000.5/Documentation/ScriptReference/UIElements.ListView.html - `BaseVerticalCollectionView` (`itemsSource`, `selectionChanged`, `selectionType`, `SetSelection`, `RefreshItems`, `Rebuild`): https://docs.unity3d.com/6000.5/Documentation/ScriptReference/UIElements.BaseVerticalCollectionView.html - `ProgressBar`: https://docs.unity3d.com/6000.5/Documentation/ScriptReference/UIElements.ProgressBar.html - `Image.sprite`: https://docs.unity3d.com/6000.5/Documentation/ScriptReference/UIElements.Image-sprite.html - `VisualElement.SetEnabled`: https://docs.unity3d.com/6000.5/Documentation/ScriptReference/UIElements.VisualElement.SetEnabled.html - `VisualElement.EnableInClassList`: https://docs.unity3d.com/6000.5/Documentation/ScriptReference/UIElements.VisualElement.EnableInClassList.html - `Focusable.Focus`: https://docs.unity3d.com/6000.5/Documentation/ScriptReference/UIElements.Focusable.Focus.html - `PanelRenderer.RegisterUIReloadCallback` (6000.5): https://docs.unity3d.com/6000.5/Documentation/ScriptReference/UIElements.PanelRenderer.RegisterUIReloadCallback.html - `UIDocument` (listed under *UI Toolkit/Legacy* in 6000.5): https://docs.unity3d.com/6000.5/Documentation/ScriptReference/UIElements.UIDocument.html - Input System 1.20 `InputActionReference`: https://docs.unity3d.com/Packages/[email protected]/api/UnityEngine.InputSystem.InputActionReference.html - [[UI Toolkit and Diegetic UI]], [[3.HUD and Inventory Example]], [[Menus, Pause and Settings Flow]]