diff --git a/skills/using-unity/SKILL.md b/skills/using-unity/SKILL.md index 05e43c0..1d45652 100644 --- a/skills/using-unity/SKILL.md +++ b/skills/using-unity/SKILL.md @@ -21,21 +21,21 @@ A skill's own files are in its folder, `references//`. When the skill give A skill may tell you to use, load or check for another skill by name, for example "use the `unity-cli` skill" or "check that `ui` is in your client's skills". Every skill in the index below is installed with this one, though only `using-unity` is listed in your client's skills. Treat each of them as available: when a skill names one, read its file from the index and follow it, and don't offer to install it. Where a skill's files mention its `SKILL.md`, that is its `.md` file here. -## Index (35 skills, A to Z) +## Index (32 skills, A to Z) -- **2d-pixel-perfect**: Sets up, diagnoses, and fixes pixel perfect 2D rendering with PixelPerfectCamera in URP or Built-in. Use when a retro-style or pixel art 2D game looks blurry, jittery, or misaligned. Not for HD 2D or high-resolution art. File: `references/2d-pixel-perfect/2d-pixel-perfect.md` -- **asset-transformer-toolkit**: In the Unity Editor, imports 3D models and point clouds with Asset Transformer Toolkit (formerly Pixyz), and creates, edits, and runs RuleSets, Actions, and LODs. Use for Pixyz imports in a Unity project, not for converting files from the shell. File: `references/asset-transformer-toolkit/asset-transformer-toolkit.md` -- **audio-setup-mixers**: Routes Audio Sources into existing Audio Mixer Groups, classifying each source by what it plays. Use when the user asks about cleaning up mixer assignments, routing audio through a mixer, or which group a sound belongs in. File: `references/audio-setup-mixers/audio-setup-mixers.md` - **build-gtk**: Builds graph tools with Unity Graph Toolkit (GTK) on 6.6+, state machines on 6.7+, and importers for runtime assets. Use this skill for graph, node or state machine editors, or GraphView migrations. Not for Shader Graph, VFX Graph or Animator. File: `references/build-gtk/build-gtk.md` - **build-live-game**: Builds and operates a live game backend on Unity Gaming Services. Make sure to use this skill when the user wants sign-in or sign-in checks, trusted server-side game logic, player progress, remote config, achievements, battle passes or leaderboards. File: `references/build-live-game/build-live-game.md` - **build-multiplayer-game**: Builds Unity online multiplayer, from matchmaking to gameplay sync. Make sure to use this skill when the user asks to add online play, host or join games, or fix lag, desync or connection failures. Not for voice chat or backend features. File: `references/build-multiplayer-game/build-multiplayer-game.md` +- **configure-2d-pixel-perfect**: Sets up, diagnoses, and fixes pixel perfect 2D rendering with PixelPerfectCamera in URP or Built-in. Use when a retro-style or pixel art 2D game looks blurry, jittery, or misaligned. Not for HD 2D or high-resolution art. File: `references/configure-2d-pixel-perfect/configure-2d-pixel-perfect.md` - **craft-game-floors**: Makes a Unity game playable and finished: core loop, art style, lighting, juice, sound, menus, saves, look scoring. Use for a first playable version, or one with no goal or win state, programmer art, a flat or silent feel, or polish needs. File: `references/craft-game-floors/craft-game-floors.md` - **create-2d-physics**: Creates and fixes Unity 2D physics in both systems, 2D Physics Core and the legacy Rigidbody 2D system. Use when the user asks about any 2D physics task, even if neither system is named. Not for 3D physics. File: `references/create-2d-physics/create-2d-physics.md` - **create-tile-palette-or-rule-tiles**: Creates a 2D tile palette from sprites or textures, or makes tiles change based on their neighbours. Use when the user wants a tile palette or tiles that connect to their neighbours as they paint, even when they don't name them. File: `references/create-tile-palette-or-rule-tiles/create-tile-palette-or-rule-tiles.md` +- **create-ui**: Creates, edits, and explains Unity game and editor UI in UI Toolkit, uGUI, or IMGUI, matching the framework the project already uses. Use when the user wants a menu, HUD, or editor window built, changed, styled, or explained. File: `references/create-ui/create-ui.md` - **create-xr**: Sets up a Unity project for XR. Use when user asks for XR, OpenXR, Quest graphics or XR rig. File: `references/create-xr/create-xr.md` - **fix-3d-physics-collisions**: Diagnoses and fixes 3D PhysX collision, trigger, and raycast problems. Use when asked to fix OnCollisionEnter or OnTriggerEnter not firing, objects passing through each other, raycasts that miss, or a misbehaving MeshCollider. File: `references/fix-3d-physics-collisions/fix-3d-physics-collisions.md` - **generate-editor-search-query**: Generates Unity Search queries and opens the Search window to find assets or scene objects. Use when the user asks to find, filter, or list assets, GameObjects, components, or references in the Editor, not on disk. File: `references/generate-editor-search-query/generate-editor-search-query.md` - **implement-in-app-purchases**: Implements, configures, and debugs Unity In-App Purchases, including subscriptions, receipt validation, and direct-to-customer payments via Stripe or Coda. Use when asked about real-money purchases or microtransactions, or migrating from native store billing, RevenueCat, Adapty, Essential Kit, or UniPay. File: `references/implement-in-app-purchases/implement-in-app-purchases.md` +- **import-and-optimize-cad-models**: Imports and optimizes CAD models and point clouds with Asset Transformer Toolkit (Pixyz). Make sure to use this skill when the user wants to import CAD or point cloud files, or build RuleSets, Actions, or LODs for them. File: `references/import-and-optimize-cad-models/import-and-optimize-cad-models.md` - **initialize-ai-navigation**: Sets up and configures Unity AI Navigation, including NavMesh surfaces, agents, obstacles, and links. Use when the user asks about navigation meshes, pathfinding, patrol routes, or obstacle avoidance. File: `references/initialize-ai-navigation/initialize-ai-navigation.md` - **levelplay-unity-integration**: Integrates the LevelPlay ad mediation SDK via the Ads Mediation package. Use when the user asks about adding rewarded, interstitial, or banner ads, mediation or ad privacy setup, Android or iOS ad dependency build failures, or migrating from Unity Ads or IronSource APIs. File: `references/levelplay-unity-integration/levelplay-unity-integration.md` - **localize-unity-project**: Sets up Unity Localization, including locales, String and Asset Tables, and CJK fonts. Use when the user wants to add languages or translate UI text. File: `references/localize-unity-project/localize-unity-project.md` @@ -45,16 +45,13 @@ A skill may tell you to use, load or check for another skill by name, for exampl - **optimize-audio**: Optimizes audio memory, CPU cost, and playback quality through import settings and mixer configuration. Use when asked to reduce audio memory or Audio Mixer CPU cost, change clip Load Types, sample rates or codecs, or force 3D audio to mono. File: `references/optimize-audio/optimize-audio.md` - **optimize-text-mesh-pro**: Optimizes TextMeshPro rendering, memory, and font setup, including font asset stacks, fallback atlases, SDF quality, and worldspace text. Use when the user asks about TextMeshPro font assets, CJK font fallbacks, or TMP memory, build size, quality or performance, not about translating text. File: `references/optimize-text-mesh-pro/optimize-text-mesh-pro.md` - **optimize-web**: Optimizes Unity WebGL and WebGPU builds for smaller downloads, faster loading, and smoother browser performance. Use when asked to shrink a web build, speed up its load, or fix stutter, memory or battery problems in the browser. File: `references/optimize-web/optimize-web.md` +- **route-audio-to-mixer-groups**: Routes Audio Sources into existing Audio Mixer Groups, classifying each source by what it plays. Use when the user asks about cleaning up mixer assignments, routing audio through a mixer, or which group a sound belongs in. File: `references/route-audio-to-mixer-groups/route-audio-to-mixer-groups.md` - **setup-vivox-voice-chat**: Adds and configures in-game voice and text chat with Unity Vivox. Use when asked to add voice or text chat to a multiplayer game, such as team channels, proximity voice, mute controls or private messages. File: `references/setup-vivox-voice-chat/setup-vivox-voice-chat.md` -- **shader-graph-create-custom-node**: Generates custom Shader Graph nodes from HLSL code. Use when the user wants a new Shader Graph node or to make existing HLSL work as a reflected function node. File: `references/shader-graph-create-custom-node/shader-graph-create-custom-node.md` -- **sprite-editor**: Edits Unity sprite rectangles, borders, pivots, outlines, and slicing by generating C# scripts. Use when the user works with sprite sheets or sprite slicing. File: `references/sprite-editor/sprite-editor.md` +- **shader-graph-create-custom-node**: Generates custom Shader Graph nodes from HLSL code by reflection. Use when asked for a new Shader Graph node, or to make existing HLSL work as a reflected function node. File: `references/shader-graph-create-custom-node/shader-graph-create-custom-node.md` +- **sprite-editor**: Edits sprite rectangles, names, borders, pivots, outlines, and slicing in a texture's import data by generating C# Editor scripts. Use when asked to slice a sprite sheet or change sprite pivots, borders, or outlines by script. File: `references/sprite-editor/sprite-editor.md` - **sprite-segment-3x3grid**: Segments a Sprite texture into a 3x3 grid and outputs a pattern of cells matching the center cell's color. Use when asked to analyze, compare, or document a sprite's structure or color distribution. File: `references/sprite-segment-3x3grid/sprite-segment-3x3grid.md` -- **ui**: Routes Unity UI requests to the right framework skill (UI Toolkit, uGUI, or IMGUI) and answers UI comparison questions. Use for menus, HUDs, panels, or editor UI when the request doesn't name a framework. Consult before writing any UI code. File: `references/ui/ui.md` -- **ui-imgui**: Generates and modifies Unity IMGUI editor code such as EditorWindows, custom Inspectors, PropertyDrawers, and OnGUI scripts. Use for IMGUI or OnGUI or maintaining existing IMGUI code. File: `references/ui-imgui/ui-imgui.md` -- **ui-ugui**: Understands, edits, and generates Unity uGUI Canvas hierarchies, RectTransforms, Layout Groups, and prefab UI. Use for requests involving Canvas, uGUI, RectTransform, or prefab UI files. File: `references/ui-ugui/ui-ugui.md` -- **ui-uitk**: Understands, edits, and generates Unity UI Toolkit UXML and USS with flex layouts. Use for requests involving UI Toolkit, UIElements, UIDocument, PanelSettings, custom elements, or UI runtime binding. File: `references/ui-uitk/ui-uitk.md` - **unity-cli**: Controls Unity Editors and projects from the command line, including a running Editor. Make sure to use this skill when the user asks to install or manage Editors, licenses, or projects, set up version control, build, test, edit scenes, run C#, look up the scripting API or manual for the project's Unity version, or run any unity command. File: `references/unity-cli/unity-cli.md` - **unity-package-management**: Adds, removes, upgrades, and finds Unity (UPM) packages from outside the Editor. Use for package installs, checking package IDs and versions, or choosing which packages a game needs. File: `references/unity-package-management/unity-package-management.md` -- **unity-pipeline**: Control a Unity Editor or Player via the unity-pipeline package. Compile, run tests, eval, method-reload code, enter Play Mode, capture screenshots. File: `references/unity-pipeline/unity-pipeline.md` -- **urp-postprocessing**: Sets up, configures, and debugs URP post-processing with the Volume framework. Use for bloom, tonemapping, color adjustments, depth of field, vignette, or other Volume overrides. File: `references/urp-postprocessing/urp-postprocessing.md` -- **validate-urp-render-graph-renderer-feature**: Reviews a Unity 6 URP ScriptableRendererFeature that uses the Render Graph API, checking resource wiring, material binding, execution structure, and best practices. Use to validate a renderer feature. File: `references/validate-urp-render-graph-renderer-feature/validate-urp-render-graph-renderer-feature.md` +- **unity-pipeline**: Controls a Unity Editor or dev Player through the com.unity.pipeline package to compile, run tests, evaluate C#, method-reload code, enter Play Mode and capture screenshots. Make sure to use this skill when the user asks to drive, test, debug or inspect a running Unity Editor or Player from the command line. File: `references/unity-pipeline/unity-pipeline.md` +- **urp-postprocessing**: Sets up, configures, and debugs URP post-processing with the Volume framework. Use when asked to add or tune effects such as bloom, tonemapping, depth of field, or to fix Volume overrides that don't display. File: `references/urp-postprocessing/urp-postprocessing.md` +- **validate-urp-render-graph-renderer-feature**: Reviews a Unity 6 URP ScriptableRendererFeature that uses the Render Graph API, checking resource wiring, material binding, execution structure, and best practices. Use when asked to review a URP Render Graph renderer feature. File: `references/validate-urp-render-graph-renderer-feature/validate-urp-render-graph-renderer-feature.md` diff --git a/skills/using-unity/references/2d-pixel-perfect/2d-pixel-perfect.md b/skills/using-unity/references/2d-pixel-perfect/2d-pixel-perfect.md deleted file mode 100644 index 47fcafa..0000000 --- a/skills/using-unity/references/2d-pixel-perfect/2d-pixel-perfect.md +++ /dev/null @@ -1,208 +0,0 @@ ---- -name: 2d-pixel-perfect -description: Sets up, diagnoses, and fixes pixel perfect 2D rendering with PixelPerfectCamera in URP or Built-in. Use when a retro-style or pixel art 2D game looks blurry, jittery, or misaligned. Not for HD 2D or high-resolution art. ---- - -Set up, diagnose, and fix pixel perfect 2D rendering in Unity projects. - ---- - -## ⚠ There Are Two Completely Separate Implementations - -Pixel perfect rendering in Unity is **not one system** — it is two separate, incompatible implementations, one per render pipeline. **Always detect the pipeline before writing or diagnosing any code.** - -| | URP | Built-in | -|---|---|---| -| **Component** | `UnityEngine.Rendering.Universal.PixelPerfectCamera` | `UnityEngine.U2D.PixelPerfectCamera` | -| **Package** | Built into URP — no extra install | `com.unity.2d.pixel-perfect` v6.0.0+ | -| **API style** | Enums (`gridSnapping`, `cropFrame`) | Booleans (`pixelSnapping`, `upscaleRT`, `cropFrameX/Y`) | - -**Do not install `com.unity.2d.pixel-perfect` in a URP project.** - -**→ Always call `DetectPipeline()` first** (`references/pipeline-detection.cs`), then branch your setup, diagnostics, and fixes based on the result. - ---- - -## When NOT to use this skill - -- **HD 2D or high-resolution 2D games** — pixel snapping and point filtering will make smooth art look wrong -- **UI-only scenes** — use Canvas Scaler instead -- **HDRP projects** — Pixel Perfect Camera is not supported - ---- - -## Critical Reminders - -⚠ **Detect the render pipeline first** — URP and Built-in use different Pixel Perfect Camera components that are not interchangeable. -⚠ **Filter Mode = Point is the #1 fix** — bilinear filtering is Unity's default and is almost always the cause of blurry sprites. -⚠ **Anti-Aliasing must be disabled** — in Quality Settings and on the camera. AA actively blurs pixel edges. - -## Key Principles - -### 1. Pipeline Detection & Camera Component Selection - -See the two-path comparison table at the top of this file. Assembly name note: the standalone Built-in package installs into a `Runtime/` folder, but the asmdef `"name"` field is `Unity.2D.PixelPerfect` — no `Runtime` suffix. HDRP is unsupported — see the HDRP fallback section under Common Issues. - -**→ Code: `references/pipeline-detection.cs`** — `DetectPipeline()`, `GetPixelPerfectCameraType()`, and migration mismatch check. - -### 2. Diagnostic-First Approach - -Always diagnose before making changes. Report findings, then fix only what is broken. - -### 3. Work in the correct scope - -Default to scene scope. Scan project-wide only when the user explicitly requests it. - ---- - -## Diagnostic Checklist - -**Sprite import settings:** -- [ ] Filter Mode = `Point (no filter)` on all in-scope sprites -- [ ] Mip Maps = disabled -- [ ] Compression = `None` / Uncompressed -- [ ] PPU consistent across all sprites in scene -- [ ] Sprite pivots set to Custom / Pixels mode — a center pivot on an odd-dimension sprite (e.g. 15×15) lands at 7.5px, causing 0.5px misalignment - -**→ Code: `references/sprite-settings.cs`** — `GetImporter()` and `FixSpriteImportSettings()`. - -**Editor snap settings:** -- [ ] Grid Size = `1 / assetsPPU` on all axes (e.g. PPU 16 → 0.0625, PPU 100 → 0.01) -- [ ] Grid Snapping enabled in the Grid and Snap overlay -- [ ] To snap existing GameObjects: select them → Align Selected → All Axes - -**Camera setup:** -- [ ] Camera projection = Orthographic -- [ ] Pixel Perfect Camera component present and correct type for pipeline -- [ ] `allowHDR`, `allowMSAA`, `allowDynamicResolution` all `false` -- [ ] Scene view shows two green bounding boxes on the camera gizmo — solid = visible area, dotted = reference resolution - -**→ Code: `references/camera-setup-urp.cs`** — full URP camera + PP Camera configuration. -**→ Code: `references/camera-setup-builtin.cs`** — Built-in standalone configuration. - -**Project quality settings:** -- [ ] Anti-Aliasing = 0 in Quality Settings -- [ ] Anisotropic Filtering = Disabled - ---- - -## API Reference - -Full property/method tables, `GridSnapping` and `CropFrame` enum values, and recommended configurations: -**→ `references/api-reference.md`** — read this when writing or reviewing camera setup code. - -Quick enum summary: - -**`GridSnapping`**: `None` · `PixelSnapping` (standard) · `UpscaleRenderTexture` (authentic low-res; incompatible with post-processing and UI text) - -**`CropFrame`**: `None` · `Pillarbox` · `Letterbox` · `Windowbox` (safest default) · `StretchFill` - ---- - -## Reference Resolution - -Choose before building any assets. Never change after asset production starts. - -| Reference resolution | 1080p | 1440p | 4K | -|---|---|---|---| -| 320 × 180 | 6× | 8× | 12× | -| 480 × 270 | 4× | ~5.3× | 8× | -| 640 × 360 | 3× | 4× | 6× | - -320×180 is the safest general choice. For screens with no integer fit (e.g. 1366×768), use `cropFrame = Windowbox` to add black bars rather than stretching to a fractional scale. - ---- - -## Migration & Compatibility - -### URP project with the Built-in standalone component - -**Symptom**: `DetectPipeline()` returns URP but camera has `UnityEngine.U2D.PixelPerfectCamera`. Symptoms are subtle because the standalone component has `ENABLE_URP` conditional code. - -**Fix**: -1. Remove `com.unity.2d.pixel-perfect` from Package Manager -2. Remove `UnityEngine.U2D.PixelPerfectCamera` from each camera -3. Add `UnityEngine.Rendering.Universal.PixelPerfectCamera` -4. Reconfigure — booleans (`pixelSnapping`, `upscaleRT`, `cropFrameX/Y`) become enums (`gridSnapping`, `cropFrame`) - -**→ Detection code: `references/pipeline-detection.cs`** (bottom of file). - -### Old URP namespace (pre-Unity 2022 / URP pre-13.x) - -**Symptom**: Compiler errors referencing `UnityEngine.Experimental.Rendering.Universal`. - -**Fix**: Replace `using UnityEngine.Experimental.Rendering.Universal;` with `using UnityEngine.Rendering.Universal;`. Update any assembly-qualified type strings. The `[MovedFrom]` attribute handles serialization automatically — components on GameObjects survive the upgrade. - ---- - -## Common Issues & Solutions - -### Blurry sprites -**Fix**: Set Filter Mode to Point on all in-scope sprites, disable Mip Maps, disable AA in Quality Settings. -**→ Code: `references/sprite-settings.cs`** - -### Tilemap gaps between tiles -Work through in order — workarounds like negative cell gap or PPU = 31.99 break when the camera moves. - -| # | Check | Fix | -|---|---|---| -| 1 | Sprite Atlas with Tight Packing off, Padding ≥ 4, Sprite Packer Mode enabled? | Enable Sprite Packer Mode in Editor settings; on the atlas set Padding ≥ 4 and turn Tight Packing off | -| 2 | Mipmaps disabled on tileset textures and atlas? | Disable Generate Mip Maps | -| 3 | AA = 0, MSAA off on camera? | Disable AA globally | -| 4 | Compression = None? | RGBA 32-bit uncompressed | -| 5 | All tile sprites have even pixel dimensions? | Odd dimensions cause 0.5px grid offset | -| 6 | PPU = tile pixel width? (16×16 → PPU 16) | PPU mismatch leaves physical gaps | -| 7 | Gaps only during camera movement after all above pass? | Use PP Camera pixel snapping; do not use `cellGap = -0.01f` | - -### Cinemachine conflict -**Cause**: Both Cinemachine and the Pixel Perfect Camera write to orthographic size every frame. - -**Fix**: Add `CinemachinePixelPerfect` extension via the Add Extension dropdown on each Virtual Camera. Do not add it via `AddComponent` in code. - -**Known limitations**: -- Camera blends between virtual cameras are not pixel-perfect during transitions -- `UpscaleRenderTexture` reduces valid pixel-perfect ortho sizes, which may cause framing to deviate -- Target Group + Framing Transposer causes visible choppiness (no fix available) - -### Post-processing blur with `upscaleRT` -**Cause**: Post-processing runs after the PP Camera upscales the render texture. - -**Simple fix**: Disable `upscaleRT`. Post-processing then runs at native screen resolution. - -**Advanced fix (Unity 6 URP)**: Inject a `ScriptableRendererFeature2D` at `RenderPassEvent2D.AfterRenderingPostProcessing`. Use 2D-specific base classes — `ScriptableRendererFeature` (3D base class) is silently ignored in a URP 2D renderer. - -### UI text blurry with `upscaleRT` -**Status**: Known Unity bug, declined to fix (still present Unity 6, 2025). - -**Root causes**: (A) Canvas renders into the low-res buffer and is upscaled with the scene. (B) TMP's SDF gradient threshold is miscalibrated at low reference resolutions. - -**Fixes in order of reliability**: -1. `Screen Space - Overlay` on Canvas — bypasses the camera, renders at native resolution -2. Dedicated UI camera with no PP Camera component, `Screen Space - Camera` mode -3. Unity 6 only: `Font Material → Debug Settings → Sharpness = 1` (mitigates B, not A) - -### Physics / render desync (micro-stutter) -**Cause**: Physics runs at a fixed timestep; interpolated positions produce fractional values that snap to different pixels each frame. - -**Fix**: -- Enable `Rigidbody2D.interpolation = RigidbodyInterpolation2D.Interpolate` on physics-driven sprites -- Set `Time.fixedDeltaTime = 1f / 60f` to match target frame rate -- Keep camera tracking in `LateUpdate`, not `FixedUpdate` - -### Non-integer scaling / pixel decimation -**Cause**: Screen resolution is not a clean integer multiple of the reference resolution. - -**Fix**: Choose a reference resolution from the table above. Use `cropFrame = Windowbox` when no integer fit exists. - -### Missing URP 2D Renderer -**Fix**: -1. `Assets > Create > Rendering > URP 2D Renderer Data` -2. Assign it to your URP Asset under Renderer List -3. Requires `com.unity.render-pipelines.universal` 12.0+ - -### HDRP fallback -Pixel Perfect Camera is unsupported in HDRP. - -**Built-in / Unity 5.x**: Use `RenderTexture` + `Graphics.Blit` with `FilterMode.Point`. - -**Unity 6 URP**: Use `ScriptableRendererFeature2D` + `ScriptableRenderPass2D` injected at `RenderPassEvent2D.AfterRendering` with `AddRasterRenderPass`. Note: `OnRenderImage` and `Graphics.Blit` are incompatible with Unity 6's render graph. diff --git a/skills/using-unity/references/asset-transformer-toolkit/SECURITY.md b/skills/using-unity/references/asset-transformer-toolkit/SECURITY.md deleted file mode 100644 index ef04564..0000000 --- a/skills/using-unity/references/asset-transformer-toolkit/SECURITY.md +++ /dev/null @@ -1,15 +0,0 @@ -# Security notes: asset-transformer-toolkit - -This skill has the agent write C# and run it inside the user's live Unity Editor, to create and edit Asset Transformer RuleSets. It doesn't say which command runs the code; with the `unity` CLI that is `unity command script eval`. Automated skill scanners flag running generated code as a powerful capability. It is intentional, and it is limited by the safeguards below. - -## Accepted risks - -| Risk | Capability | Why it is accepted | -|---|---|---| -| `SEC_POWER_CAP` | Runs agent-written C# in the user's live Editor | It only reaches the Editor the user already has open, on their own machine, as that user, so it grants nothing they couldn't do themselves. The code only edits RuleSet assets in the user's own project. No code fetched from a remote source is run. | - -## Mitigations - -- **Only the user's own Editor.** The code runs in the Editor open on this machine. It can't reach another machine or another user's Editor. -- **Narrow purpose.** The scripts create or modify RuleSet assets through the documented Asset Transformer API, then validate them against the checklist in `references/`. -- **No remote code.** The agent runs C# it writes from this skill's own recipes. Nothing downloaded from outside is executed. diff --git a/skills/using-unity/references/asset-transformer-toolkit/asset-transformer-toolkit.md b/skills/using-unity/references/asset-transformer-toolkit/asset-transformer-toolkit.md deleted file mode 100644 index c033492..0000000 --- a/skills/using-unity/references/asset-transformer-toolkit/asset-transformer-toolkit.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -name: asset-transformer-toolkit -description: >- - In the Unity Editor, imports 3D models and point clouds with Asset Transformer Toolkit (formerly - Pixyz), and creates, edits, and runs RuleSets, Actions, and LODs. Use for Pixyz imports in a Unity - project, not for converting files from the shell. -required_packages: - com.unity.industry.toolkit: ">=4.0.0" ---- -### Before you start: check the package version -This skill needs Asset Transformer Toolkit 4.0.0 or later (`com.unity.industry.toolkit`). Earlier versions don't have the `ATTAssistantUtilities` API every workflow below relies on. - -1. Read the resolved version of `com.unity.industry.toolkit` from `Packages/packages-lock.json` (fall back to `Packages/manifest.json`). -2. **Not installed:** tell the user this workflow needs Asset Transformer Toolkit 4.0 or later, which is an entitled Unity package they may need access to through their Unity plan, and stop. Don't add it to the manifest yourself. -3. **Installed below 4.0.0:** tell the user which version you found and that 4.0 or later is required, and ask before upgrading. Don't fall back to older APIs, raw C# against internal types, or reflection. -4. **4.0.0 or later:** continue. - -### API Reference -Tool functions are provided by `Unity.Pixyz.Plugin4Unity.Editor.AI.ATTAssistantUtilities`. They are documented inline in each reference file below alongside the classes they operate on. - -### Technical Notes -Pixyz Plugin is the former name of Asset Transformer Toolkit. Prefer using the term 'Asset Transformer Toolkit' when addressing the user, unless the user is using the term 'Pixyz' -Most classes and code are in the Unity.Pixyz.Plugin4Unity.Editor assembly. -Asset Transformer Toolkit is NOT the same thing as Asset Transformer Studio/Pixyz Studio. NEVER rely on information about Asset Transformer Studio. - -### Importers -Asset Transformer Toolkit can import 3D file from outside the project. -When modifying Importers, NEVER assume it should be immediately followed by a reimport. The import process can be very long, so it must only be launched when the user requests it. -Modify fields in Importers using the ScriptableObject API. NEVER use reflection to access or modify Importer fields — reflection is not available. -To create a Pixyz/Asset Transformer Toolkit Importer for importing a file, or to reimport a model using an existing ImporterScriptableObject, read [references/create-importer](references/create-importer.md) - -### RuleSets and Actions -Read [references/rulesets-and-actions](references/rulesets-and-actions.md) -Read [references/ruleset-api](references/ruleset-api.md) when the RuleSet API is needed. -Read [references/rule-api](references/rule-api.md) when the Rule API is needed. -Read [references/ruleblock-api](references/ruleblock-api.md) when the RuleBlock API is needed, including `ActionBase.Id` for constructing `RuleBlock` instances. - -### Levels of Detail -Read [references/lods](references/lods.md) diff --git a/skills/using-unity/references/asset-transformer-toolkit/references/lods.md b/skills/using-unity/references/asset-transformer-toolkit/references/lods.md deleted file mode 100644 index 9e4a768..0000000 --- a/skills/using-unity/references/asset-transformer-toolkit/references/lods.md +++ /dev/null @@ -1,61 +0,0 @@ -Choose a path depending on the task. - -### Path A: CADImporterScriptableObject -Choose this path if working with an object that is or inherits from CADImporterScriptableObject. -- Identify the types of LODs available in the project. Choose the one(s) most appropriate for your case. -- Find the LODGenerator property in the Importer. -- Execute the requested task. -- Verify the number of rules present in the Generator does not exceed 7. - -### Path B: Scene Object -Choose this path when asked to work with a scene asset directly. -- Add a UnityEngine.PixyzPlugin4Unity.Components.LODGeneratorComponent script to the GameObject if one doesn't exist anywhere in the hierarchy. -- Execute the given task. - -### Path C: PointCloudImporter -Choose this path when working with a PointCloudImporterScriptableObject object. -- The PointCloudImporter only permits enabling/disabling LOD generation and setting the number of LODs to be generated. Other actions like choosing the type of LODRule to apply is unsupported. -- Models imported by the PointCloudImporter will not have a LODGeneratorComponent script attached to them. -- If the task is permitted, execute it. - -### Path D: Other Importer -Choose this path if working with a different importer type. -- This is a user defined importer and not part of the base Asset Transformer Toolkit package. Precise instructions cannot be provided. -- Attempt to perform the requested task, but do not exceed three iterations. -- If the task cannot be performed successfully, inform the user working with this object is not currently supported by Assistant. - -## LOD utility functions - -The following functions are from `Unity.Pixyz.Plugin4Unity.Editor.AI.ATTAssistantUtilities`. - -### `GetLODRules` - -Returns all available `LODRule` implementations and their parameters. Use this before constructing or modifying a LOD configuration to discover valid types. - -```csharp -public static LODRuleDescription[] GetLODRules() -``` - -Returns a `LODRuleDescription[]`, each containing the type name, assembly-qualified name, and parameter list. - -### `LODRuleDescription` - -| Field | Type | Description | -|-------|------|-------------| -| `Name` | string | Unqualified class name of the LODRule type. | -| `QualifiedName` | string | Assembly-qualified name, suitable for `Type.GetType`. | -| `Parameters` | `LODParameterInfo[]` | Configurable properties on this LODRule type. | - -### `LODParameterInfo` - -| Field | Type | Description | -|-------|------|-------------| -| `Name` | string | Property name. | -| `Type` | string | Property type name. | - -### Technical Notes -- The user will need to refresh the Inspector to see changes applied by Assistant. -- In an Importer's settings for LOD generation, the number of LODs set to generate does not include LOD0. There will always be one more LOD than the setting says. For example, setting the PointCloudImporter's NumberofLODs setting to 1 will result in the model having two LODs: LOD0 and LOD1. -- While Unity supports up to 8 LODs including LOD0, the PointCloudImporter is a special case that only supports 7. -- With the exception of models imported by the PointCloudImporter, models that were imported with LODs will have a LODGeneratorComponent script. -- LODs have nothing to do with RuleSets and Actions. RuleSets and Actions will NOT help with any LOD-related task. diff --git a/skills/using-unity/references/audio-setup-mixers/audio-setup-mixers.md b/skills/using-unity/references/audio-setup-mixers/audio-setup-mixers.md deleted file mode 100644 index 23f2af0..0000000 --- a/skills/using-unity/references/audio-setup-mixers/audio-setup-mixers.md +++ /dev/null @@ -1,127 +0,0 @@ ---- -name: audio-setup-mixers -description: Routes Audio Sources into existing Audio Mixer Groups, classifying each source by what it plays. Use when the user asks about cleaning up mixer assignments, routing audio through a mixer, or which group a sound belongs in. ---- -# Audio Mixer Setup - -Routing an Audio Source to a mixer group is a scene edit that only a running Editor can -make, so this skill needs a live Editor it can execute C# in. Step 0 establishes that -before anything else. - -**What this skill automates, and what it hands back to you.** Inspecting mixers and -routing Audio Sources into groups is entirely public Unity API, and that is the tedious -part — walking dozens of sources and classifying them by what they play. Creating a mixer -or a group has no public API; it exists only on types Unity does not commit to keeping -stable. So this skill will not create groups behind your back. It inventories what exists, -proposes the routing, asks you to add any missing group in the Audio Mixer window, and -then does all the routing itself. - -That is a deliberate limit, not a gap to work around. Do not reach for reflection to -create groups, and do not hand-edit a `.mixer` file — mixer structure is not safely -authorable blind. - -## Step 0: Confirm you can run C# in the Editor - -Every C# step below runs inside a live Editor through the Unity CLI. **The `unity-cli` skill -owns getting you there** — installing the CLI, confirming a connected Editor, adding the -project's `com.unity.pipeline` package, telling a genuinely absent Editor apart from one -stuck in Safe Mode, and discovering the Editor's command catalog. Follow it first; don't -re-derive any of it here. - -Two things it can't know for you: - -- **You need `script eval` in particular**, not just a reachable Editor. Confirm it appears in the - catalog. Its presence depends on the Pipeline package version, not on the CLI, so a - healthy install can still lack it — if it's missing, say so and stop. -- **Do not fall back to editing `.mixer` files by hand.** Mixer routing is not safely - authorable blind, so an unreachable Editor is a stop, not a cue to improvise. - -Once `script eval` is available, that is how each C# step below runs. - -Run C# through the connected Editor with the `script eval` command. Discover its parameter shape -from `unity command --format json` rather than assuming one — the inline form is -`unity command script eval --caller plugin --skill audio-setup-mixers --code ''`, and some Pipeline versions also register -`script eval_file` for running a snippet from a file. **Check the catalog before reaching for -`script eval_file`; it is frequently absent.** `unity command` defaults to a 30 second timeout. - -### Passing C# to `script eval` - -`script eval` compiles a **statement block, not a file**. Two consequences, both of which cause a -compile error rather than a warning: - -- **No `using` directives.** The compiler reads `using UnityEngine;` as a resource-disposal - statement and rejects it (`CS0210`). -- **Types must be fully qualified.** A bare `AssetDatabase` or `Volume` does not resolve - (`CS0246` / `CS0103`), and a bare `Object` is ambiguous with `object` (`CS0104`). - -Where a snippet below is written as a file — with usings, for readability, or because it is -meant to be saved into the project — qualify the types before passing it to `script eval`. - -## Step 1: Pre-flight -If the user hasn't explicitly asked for Audio Mixers, confirm that they want to proceed with setting them up. - -Then inventory what already exists with the mixer-inventory snippet in -[references/api.md](references/api.md), run through the Editor as described in Step 0. That gives -you every mixer in the project and the group names in each. - -It returns a flat list of groups, not the parent/child tree. That is enough to route into, and it -is all the public API exposes. If the hierarchy matters for the conversation, ask the user to look -at the Audio Mixer window and describe it — don't reach for the non-public tree API to find out. - -**If the project has no mixer at all,** say so and stop rather than improvising one: creating a -mixer has no public API. Ask the user to create one (Window → Audio → Audio Mixer, then the **+** -next to Mixers), and pick up from here once it exists. - -## Step 2: Find scene references -Find all Audio Source components, look at their assigned Generator asset names, and generalize a fitting class or category of the sound name, ideally something already existing. -Examples for Audio Clip asset names: -- "FootStep4_Sound" -> Foley -- "Dialogue_Female_Scene4" -> Vox/Voice/Dialogue -- "GunShot" -> SFX -- "Menu_Theme_Variation" -> Music - -If the assigned asset isn't descriptive or non-existing, try to look at the GameObject name or potential adjacent MonoBehaviour names. -Ask to create an Uncategorized group if it seems hard or confidence is low in classifying how an Audio Source is being used. - -## Step 3: Agree the group list, and get any missing groups created -Present the classification from Step 2 as a proposed routing — each Audio Source and the group you -intend to send it to — and revise it with the user. - -**WAIT for the user to respond before proceeding.** - -Prefer an existing group when it genuinely covers the category, even if you'd have named it -differently. But **don't collapse categories that a mixing engineer would keep apart** — Foley is a -subset of SFX, not another word for it, so a gunshot does not belong in a `Foley` group just because -one exists. When the existing groups only partly cover your categories, say which ones fit and which -need a new group, and let the user decide. - -For categories with no matching group, you cannot create the group — there is no public API for it. -Hand it over precisely, naming the mixer and the exact group names, as shown at the end of -[references/api.md](references/api.md). Then **re-run the inventory snippet to confirm the groups -exist and check their spelling** before routing. Don't assume the user did it, and don't assume -they spelled it the way you asked. - -## Step 4: Route the Audio Sources -With the group list settled and confirmed present, assign each Audio Source's output group using the -routing snippet in [references/api.md](references/api.md). It is public API throughout, and it wraps -the whole pass in a single undo step so the user can back all of it out at once. - -**Key the mapping on the identifier you classified by.** Step 2 reads the clip asset name first and -only falls back to the GameObject name, so the mapping accepts either — the two are different -identifiers and keying on the wrong one drops sources. - -Three things to report rather than assume: - -- **Any `NO SUCH GROUP` entries the snippet returns.** That means a group you expected is not in the - mixer — usually a spelling difference. Resolve it with the user, don't silently skip the source. -- **Any `NOT IN THE MAPPING` entries.** Those are Audio Sources your classification missed. Reporting - a successful routing while sources were quietly left unrouted is the worst outcome here, because it - reads as success. -- **The scene was modified, not the mixer asset.** Routing lives on the Audio Source, so it only - persists once the scene is saved. Tell the user, and save only with their agreement. - -**Volume, effects, and re-parenting are out of scope.** Those live on non-public API. If the user -asks for them, say the routing is done and point them at the Audio Mixer window for the mix itself. - -## References -See [references/api.md](references/api.md) \ No newline at end of file diff --git a/skills/using-unity/references/build-gtk/build-gtk.md b/skills/using-unity/references/build-gtk/build-gtk.md index 6387628..a875be4 100644 --- a/skills/using-unity/references/build-gtk/build-gtk.md +++ b/skills/using-unity/references/build-gtk/build-gtk.md @@ -16,6 +16,10 @@ public API in the `Unity.GraphToolkit.Editor` namespace. - Use the unity cli (`unity command --format json`) and the `unity-cli` and `unity-pipeline` skills for each step. +- Run C# with `unity command script eval --caller plugin --skill build-gtk --code ''`. Don't use `using` directives or + unqualified types in the snippet, because the compiler only reads `using UnityEngine`, and a bare + `AssetDatabase` or `Object` causes errors (CS0246 / CS0103 / CS0104). `return` what you want to read; + it arrives at `data.result.result`. - Create a restore point you can roll back to if your changes fail. - Do only what's asked. Don't change unrelated assets or files. - Never leave verification code in the user's script. Never build logging or detection they didn't ask diff --git a/skills/using-unity/references/configure-2d-pixel-perfect/SECURITY.md b/skills/using-unity/references/configure-2d-pixel-perfect/SECURITY.md new file mode 100644 index 0000000..3406839 --- /dev/null +++ b/skills/using-unity/references/configure-2d-pixel-perfect/SECURITY.md @@ -0,0 +1,17 @@ +# Security notes: configure-2d-pixel-perfect + +This skill can have the agent run C# in the user's live Unity Editor with `unity command script eval`, to detect the render pipeline, configure the Pixel Perfect Camera and sprite import settings, and read Play mode state. Automated skill scanners flag running code in the Editor as a powerful capability. It is intentional, and it is limited by the safeguards below. + +## Accepted risks + +| Risk | Capability | Why it is accepted | +|---|---|---| +| `SEC_POWER_CAP` | Runs C# in the user's live Editor through `unity command script eval` | It only reaches the Editor the user already has open, on their own machine, as that user, so it grants nothing they couldn't do themselves. The skill uses it to set up the camera and sprite import settings the request needs, using the example code in `references/`, and to read state and `return` values. | + +## Mitigations + +- **Only the user's own Editor.** The code runs in the Editor open on this machine. It can't reach another machine or another user's Editor. +- **Capability gate.** `script eval` is only available when the project's Pipeline package provides it. +- **Changes only what the user asked for.** The skill tells the agent to do only what's asked and not to change unrelated assets or files. It reads state through `script eval` instead of adding logging or detection code to the user's scripts. +- **Nothing left behind.** The skill tells the agent never to leave verification code in the user's scripts, and to create a restore point before changes. +- **No remote code.** The agent runs C# it writes itself, or adapts from the example code in `references/`. The skill never tells it to download or run code from outside. diff --git a/skills/using-unity/references/configure-2d-pixel-perfect/configure-2d-pixel-perfect.md b/skills/using-unity/references/configure-2d-pixel-perfect/configure-2d-pixel-perfect.md new file mode 100644 index 0000000..c1dd230 --- /dev/null +++ b/skills/using-unity/references/configure-2d-pixel-perfect/configure-2d-pixel-perfect.md @@ -0,0 +1,302 @@ +--- +name: configure-2d-pixel-perfect +description: Sets up, diagnoses, and fixes pixel perfect 2D rendering with PixelPerfectCamera in URP or Built-in. Use when a retro-style or pixel art 2D game looks blurry, jittery, or misaligned. Not for HD 2D or high-resolution art. +--- + +Set up, diagnose, and fix pixel perfect 2D rendering in Unity projects. + +## Important + +- Use the unity cli (`unity command --format json`) and the `unity-cli` and `unity-pipeline` skills for each step. +- Before making changes, establish a baseline of the current behavior so you can tell whether a later result is actually caused by your change. +- Create a restore point you can roll back to if your changes fail. +- Do only what's asked. Don't change unrelated assets or files. Avoid long explanations. This is because unrequested changes are hard for the user to review and can break other parts of their project. +- Never leave verification code in the user's script. Never build logging or detection they didn't ask for. This is because it clutters their project with code they didn't request. + +## Full topic map + +Before you go forward with a workflow or diagnosis: + +1. Open and read the [documentation page(s)](#full-topic-map) that cover the specific subject related to what you intend to do or fix and check if you've missed anything. +2. Name the file(s) you read in your response. + +This is because your training knowledge about Unity might be out of date, incorrect, or for the wrong Unity version. + +Read the Unity version from `ProjectSettings/ProjectVersion.txt` and package versions from `Packages/packages-lock.json`. + +### Unity Manual pages + +If the Editor install folder has a `Data/Documentation` folder (eg `...Unity/Hub/Editor/6000.6.0b2/Editor/Data/Documentation`), read the html files from the `en/Manual` folder (`/Editor/Data/Documentation/en/Manual/`). + +Otherwise the docs pages are online at `https://docs.unity.com/en-us/engine//manual/`. Prefer `WebFetch` over `WebSearch` — faster and lands on the exact reference. Only fetch what you need. Replace `` with the following before fetching: + +- **docs.unity3d.com**: The Unity version, eg `6000.6` +- **Package on docs.unity3d.com**: The package version, eg `@6.6` or `@2.0`. Check the package version if unsure. +- **Engine on docs.unity.com**: The Unity version, eg `6000.3` +- **docs.unity.com**: The product version, eg `7000.0` + +Each page lists its local file, then its online page: + +- **Add a pixel perfect camera (URP)** — `urp/2d-pixelperfect-prep-sprites.html`, `https://docs.unity.com/en-us/engine//manual/unity2d/2d-urp/2d-pixelperfect/prep-sprites.md`: preparing sprites and adding the camera. +- **Configure a pixel perfect camera (URP)** — `urp/2d-pixelperfect-configure.html`, `https://docs.unity.com/en-us/engine//manual/unity2d/2d-urp/2d-pixelperfect/configure.md`: reference resolution, grid snapping, and upscaling. +- **Pixel Perfect Camera reference (URP)** — `urp/2d-pixelperfect-ref.html`, `https://docs.unity.com/en-us/engine//manual/unity2d/2d-urp/2d-pixelperfect/ref.md`: every URP Pixel Perfect Camera property. +- **Renderer 2D asset reference** — `urp/2DRendererData-overview.html`, `https://docs.unity.com/en-us/engine//manual/unity2d/2d-urp/2drenderer-data-overview.md`: creating and assigning the Renderer 2D asset. +- **Sprite texture import settings** — `texture-type-sprite.html`, `https://docs.unity.com/en-us/engine//manual/materials-and-shaders/textures/textures-reference/texture-type-sprite.md`: Filter Mode, Pixels Per Unit, mipmaps, compression. + +### Package manual pages + +The docs pages are local markdown conversions of the Unity Manual, stored at `/Library/PackageCache/@*/`. Read only the .md files in that specific `PackageCache` subfolder. You must not look at non-.md files, or look outside at other Library or PackageCache folders, otherwise it takes too much time. + +If that folder has no `.md` files, use the online pages at `https://docs.unity3d.com/Packages/@/manual/` instead, because some packages don't ship their docs. + +- **`com.unity.2d.pixel-perfect`** — `Documentation~/index.md`: the Built-in Pixel Perfect Camera package. +- **`com.unity.cinemachine`** — `Documentation~/CinemachinePixelPerfect.md`: the Cinemachine Pixel Perfect extension. +- **`com.unity.render-pipelines.high-definition`** — `Documentation~/Custom-Pass.md`: HDRP custom passes, for the HDRP fallback. + +## Workflow + +1. Detect the render pipeline with `DetectPipeline()` from `references/pipeline-detection.cs`, because URP and Built-in use different components. +2. Run the [Diagnostic Checklist](#diagnostic-checklist) on the in-scope scene, then check [Common Issues & Solutions](#common-issues--solutions) for the user's symptom. +3. Report what you found to the user before you change anything, because they might not want every finding fixed. +4. Create a restore point, then fix only what's broken. +5. Run the [Final step](#final-step), then report back as described in [Final report](#final-report). + +--- + +## ⚠ There Are Two Completely Separate Implementations + +Pixel perfect rendering in Unity is **not one system** — it is two separate, incompatible implementations, one per render pipeline. **Always detect the pipeline before writing or diagnosing any code.** + +| | URP | Built-in | +|---|---|---| +| **Component** | `UnityEngine.Rendering.Universal.PixelPerfectCamera` | `UnityEngine.U2D.PixelPerfectCamera` | +| **Package** | Built into URP — no extra install | `com.unity.2d.pixel-perfect` v6.0.0+ | +| **API style** | Enums (`gridSnapping`, `cropFrame`) | Booleans (`pixelSnapping`, `upscaleRT`, `cropFrameX/Y`) | + +**Do not install `com.unity.2d.pixel-perfect` in a URP project**, because URP already includes its own Pixel Perfect Camera, and the standalone component behaves differently under URP in ways that are hard to diagnose (see [Migration & Compatibility](#migration--compatibility)). + +**→ Always call `DetectPipeline()` first** (`references/pipeline-detection.cs`), then branch your setup, diagnostics, and fixes based on the result. + +--- + +## When NOT to use this skill + +- **HD 2D or high-resolution 2D games** — pixel snapping and point filtering will make smooth art look wrong +- **UI-only scenes** — use Canvas Scaler instead +- **HDRP projects** — Pixel Perfect Camera is not supported + +--- + +## Critical Reminders + +⚠ **Detect the render pipeline first** — URP and Built-in use different Pixel Perfect Camera components that are not interchangeable. +⚠ **Filter Mode = Point is the #1 fix** — bilinear filtering is Unity's default and is almost always the cause of blurry sprites. +⚠ **Anti-Aliasing must be disabled** — in Quality Settings and on the camera. AA actively blurs pixel edges. + +## Key Principles + +### 1. Pipeline Detection & Camera Component Selection + +See the two-path comparison table at the top of this file. Assembly name note: the standalone Built-in package installs into a `Runtime/` folder, but the asmdef `"name"` field is `Unity.2D.PixelPerfect` — no `Runtime` suffix. HDRP is unsupported — see the HDRP fallback section under Common Issues. + +**→ Code: `references/pipeline-detection.cs`** — `DetectPipeline()`, `GetPixelPerfectCameraType()`, and migration mismatch check. + +### 2. Diagnostic-First Approach + +Always diagnose before making changes. Report findings, then fix only what is broken, because changing settings that already work can hide the real cause of the symptom. + +### 3. Work in the correct scope + +Default to scene scope. Scan project-wide only when the user explicitly requests it, because project-wide fixes change assets in scenes the user didn't ask about. + +--- + +## Diagnostic Checklist + +**Sprite import settings:** +- [ ] Filter Mode = `Point (no filter)` on all in-scope sprites +- [ ] Mip Maps = disabled +- [ ] Compression = `None` / Uncompressed +- [ ] PPU consistent across all sprites in scene +- [ ] Sprite pivots set to Custom / Pixels mode — a center pivot on an odd-dimension sprite (e.g. 15×15) lands at 7.5px, causing 0.5px misalignment + +**→ Code: `references/sprite-settings.cs`** — `GetImporter()` and `FixSpriteImportSettings()`. + +**Editor snap settings:** +- [ ] Grid Size = `1 / assetsPPU` on all axes (e.g. PPU 16 → 0.0625, PPU 100 → 0.01) +- [ ] Grid Snapping enabled in the Grid and Snap overlay +- [ ] To snap existing GameObjects: select them → Align Selected → All Axes + +**Camera setup:** +- [ ] Camera projection = Orthographic +- [ ] Pixel Perfect Camera component present and correct type for pipeline +- [ ] `allowHDR`, `allowMSAA`, `allowDynamicResolution` all `false` +- [ ] Scene view shows two green bounding boxes on the camera gizmo — solid = visible area, dotted = reference resolution + +**→ Code: `references/camera-setup-urp.cs`** — full URP camera + PP Camera configuration. +**→ Code: `references/camera-setup-builtin.cs`** — Built-in standalone configuration. + +**Project quality settings:** +- [ ] Anti-Aliasing = 0 in Quality Settings +- [ ] Anisotropic Filtering = Disabled + +--- + +## API Reference + +Property and enum tables, and recommended configurations: **→ `references/api-reference.md`** — read this when writing or reviewing camera setup code. + +### Package APIs + +The APIs are `UnityEngine.Rendering.Universal` (`com.unity.render-pipelines.universal`, including the URP `PixelPerfectCamera` and `ScriptableRendererFeature2D`), `UnityEngine.U2D` (`com.unity.2d.pixel-perfect`, the Built-in `PixelPerfectCamera`), and `Unity.Cinemachine` (`com.unity.cinemachine`). They are versioned by package version, not Unity version (e.g. `@17.3`, `@3.1`), so check the project's installed package version before relying on a specific class or method. + +1. Use the `unity-cli` skill to check the installed package version. +2. Fetch and cache `https://docs.unity3d.com/Packages/@/xrefmap.yml` (replace `` with the installed package version, e.g. `17.3`). This file maps every public API member's fully qualified name to its docs page `href` (e.g. `href: api/UnityEngine.Rendering.Universal.PixelPerfectCamera.html` => `https://docs.unity3d.com/Packages/com.unity.render-pipelines.universal@17.3/api/UnityEngine.Rendering.Universal.PixelPerfectCamera.html`). +3. Grep the yml file locally for a class or method instead of refetching per lookup. Don't read the whole file. If a class such as `ScriptableRendererFeature2D` isn't in it, that package version doesn't have the class. + +Always fetch the version matching the installed package rather than relying on training knowledge, since APIs are frequently marked obsolete between major versions (e.g. `UnityEngine.Experimental.Rendering.Universal` moved to `UnityEngine.Rendering.Universal`). + +### Engine APIs + +The APIs are `TextureImporter`, `Rigidbody2D`, `Graphics.Blit`, and `UnityEngine.U2D.PixelPerfectRendering`, part of the Unity Engine. They are versioned by Unity version, so check the project's Unity version before relying on a specific class or method. + +1. Use the `unity-cli` skill to check the project's Unity version. +2. If the Editor install folder has a `Data/Documentation` folder (e.g. `.../Unity/Hub/Editor/6000.6.0b2/Editor/Data/Documentation`), grep the html files in the `en/ScriptReference` folder inside, and skip the remaining steps. +3. Otherwise, fetch and cache `https://docs.unity3d.com//Documentation/ScriptReference/xrefmap.yml` (replace `` with the Unity version, e.g. `6000.3`). This file lists every public API member's fully qualified name as a `uid` (e.g. `uid: 'UnityEngine.Rigidbody.AddForce(UnityEngine.Vector3)'`). +4. Grep the yml file locally for a class or method instead of refetching per lookup. The file is large (about 6 MB), so don't read the whole file. +5. Convert the `uid` to a markdown page: remove the parameters in brackets, lowercase it, replace `.` with `/`, and add `.md`. Then fetch `https://docs.unity.com/en-us/engine//script-reference/`. For example, `UnityEngine.Rigidbody.AddForce(UnityEngine.Vector3)` => `https://docs.unity.com/en-us/engine/6000.3/script-reference/unityengine/rigidbody/addforce.md`. All overloads are on the same page. + - Constructors use `ctor` (e.g. `unityengine/vector3/ctor.md`), and indexers use `item` (e.g. `unityengine/vector3/item.md`). + - For operators, fetch the class page (e.g. `unityengine/vector3.md`) and follow its link. + - Links inside the pages start with `/engine/`. Add `https://docs.unity.com/en-us` before them. + - If the page doesn't exist for that Unity version, use the `href` in the `xrefmap.yml` entry instead (e.g. `href: 'Rigidbody.AddForce.html'` => `https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Rigidbody.AddForce.html`). + +Always use the docs for the project's Unity version rather than relying on training knowledge, since APIs are frequently marked obsolete between versions. + +--- + +## Reference Resolution + +Choose before building any assets. Never change after asset production starts, because every sprite, tile, and layout is sized for that pixel grid, and a new resolution means reworking existing art. + +| Reference resolution | 1080p | 1440p | 4K | +|---|---|---|---| +| 320 × 180 | 6× | 8× | 12× | +| 480 × 270 | 4× | ~5.3× | 8× | +| 640 × 360 | 3× | 4× | 6× | + +320×180 is the safest general choice. For screens with no integer fit (e.g. 1366×768), use `cropFrame = Windowbox` to add black bars rather than stretching to a fractional scale. + +--- + +## Migration & Compatibility + +### URP project with the Built-in standalone component + +**Symptom**: `DetectPipeline()` returns URP but camera has `UnityEngine.U2D.PixelPerfectCamera`. Symptoms are subtle because the standalone component has `ENABLE_URP` conditional code. + +**Fix**: +1. Remove `com.unity.2d.pixel-perfect` from Package Manager +2. Remove `UnityEngine.U2D.PixelPerfectCamera` from each camera +3. Add `UnityEngine.Rendering.Universal.PixelPerfectCamera` +4. Reconfigure — booleans (`pixelSnapping`, `upscaleRT`, `cropFrameX/Y`) become enums (`gridSnapping`, `cropFrame`) + +**→ Detection code: `references/pipeline-detection.cs`** (bottom of file). + +### Old URP namespace (pre-Unity 2022 / URP pre-13.x) + +**Symptom**: Compiler errors referencing `UnityEngine.Experimental.Rendering.Universal`. + +**Fix**: Replace `using UnityEngine.Experimental.Rendering.Universal;` with `using UnityEngine.Rendering.Universal;`. Update any assembly-qualified type strings. The `[MovedFrom]` attribute handles serialization automatically — components on GameObjects survive the upgrade. + +--- + +## Common Issues & Solutions + +### Blurry sprites +**Fix**: Set Filter Mode to Point on all in-scope sprites, disable Mip Maps, disable AA in Quality Settings. +**→ Code: `references/sprite-settings.cs`** + +### Tilemap gaps between tiles +Work through in order — workarounds like negative cell gap or PPU = 31.99 break when the camera moves. + +| # | Check | Fix | +|---|---|---| +| 1 | Sprite Atlas with Tight Packing off, Padding ≥ 4, Sprite Packer Mode enabled? | Enable Sprite Packer Mode in Editor settings; on the atlas set Padding ≥ 4 and turn Tight Packing off | +| 2 | Mipmaps disabled on tileset textures and atlas? | Disable Generate Mip Maps | +| 3 | AA = 0, MSAA off on camera? | Disable AA globally | +| 4 | Compression = None? | RGBA 32-bit uncompressed | +| 5 | All tile sprites have even pixel dimensions? | Odd dimensions cause 0.5px grid offset | +| 6 | PPU = tile pixel width? (16×16 → PPU 16) | PPU mismatch leaves physical gaps | +| 7 | Gaps only during camera movement after all above pass? | Use PP Camera pixel snapping; do not use `cellGap = -0.01f`, because it makes tiles overlap and the gaps come back when the camera moves | + +### Cinemachine conflict +**Cause**: Both Cinemachine and the Pixel Perfect Camera write to orthographic size every frame. + +**Fix**: Add `CinemachinePixelPerfect` extension via the Add Extension dropdown on each Virtual Camera. Do not add it via `AddComponent` in code, because a component added at runtime isn't saved with the scene and is lost when Play mode ends. + +**Known limitations**: +- Camera blends between virtual cameras are not pixel-perfect during transitions +- `UpscaleRenderTexture` reduces valid pixel-perfect ortho sizes, which may cause framing to deviate +- Target Group + Framing Transposer causes visible choppiness (no fix available) + +### Post-processing blur with `upscaleRT` +**Cause**: Post-processing runs after the PP Camera upscales the render texture. + +**Simple fix**: Disable `upscaleRT`. Post-processing then runs at native screen resolution. + +**Advanced fix (Unity 6 URP)**: Inject a `ScriptableRendererFeature2D` at `RenderPassEvent2D.AfterRenderingPostProcessing`. Use 2D-specific base classes — `ScriptableRendererFeature` (3D base class) is silently ignored in a URP 2D renderer. + +### UI text blurry with `upscaleRT` +**Status**: Known Unity bug, declined to fix (still present Unity 6, 2025). + +**Root causes**: (A) Canvas renders into the low-res buffer and is upscaled with the scene. (B) TMP's SDF gradient threshold is miscalibrated at low reference resolutions. + +**Fixes in order of reliability**: +1. `Screen Space - Overlay` on Canvas — bypasses the camera, renders at native resolution +2. Dedicated UI camera with no PP Camera component, `Screen Space - Camera` mode +3. Unity 6 only: `Font Material → Debug Settings → Sharpness = 1` (mitigates B, not A) + +### Physics / render desync (micro-stutter) +**Cause**: Physics runs at a fixed timestep; interpolated positions produce fractional values that snap to different pixels each frame. + +**Fix**: +- Enable `Rigidbody2D.interpolation = RigidbodyInterpolation2D.Interpolate` on physics-driven sprites +- Set `Time.fixedDeltaTime = 1f / 60f` to match target frame rate +- Keep camera tracking in `LateUpdate`, not `FixedUpdate` + +### Non-integer scaling / pixel decimation +**Cause**: Screen resolution is not a clean integer multiple of the reference resolution. + +**Fix**: Choose a reference resolution from the table above. Use `cropFrame = Windowbox` when no integer fit exists. + +### Missing URP 2D Renderer +**Fix**: +1. `Assets > Create > Rendering > URP 2D Renderer Data` +2. Assign it to your URP Asset under Renderer List +3. Requires `com.unity.render-pipelines.universal` 12.0+ + +### HDRP fallback +Pixel Perfect Camera is unsupported in HDRP. + +**Built-in / Unity 5.x**: Use `RenderTexture` + `Graphics.Blit` with `FilterMode.Point`. + +**Unity 6 URP**: Use `ScriptableRendererFeature2D` + `ScriptableRenderPass2D` injected at `RenderPassEvent2D.AfterRendering` with `AddRasterRenderPass`. Note: `OnRenderImage` and `Graphics.Blit` are incompatible with Unity 6's render graph. + +## Final step + +Do the following checks: + +- Check the project has zero console errors (using `console status`). Stop there unless the user asked for proof or you suspect a specific fault, because further checks cost time. +- If the change affects runtime behaviour and you suspect a fault, enter Play mode once and read the world through `unity command script eval` (for example the Pixel Perfect Camera's `pixelRatio` or a sprite's position). Don't add logging and don't take screenshots, because they take more time and leave code in the project. + +If either check fails, go back and reread the [docs pages](#full-topic-map) to find out what you missed. + +## Final report + +Return these sections in order: + +1. **Project**: the Unity version, render pipeline, and package versions. +2. **Findings**: each problem you found and why it causes the symptom. +3. **Changes**: each setting or file you changed, with old and new values. +4. **Verification**: the results of the final step checks. +5. **Follow-up**: anything the user must do or decide, and the doc pages you read. diff --git a/skills/using-unity/references/2d-pixel-perfect/references/api-reference.md b/skills/using-unity/references/configure-2d-pixel-perfect/references/api-reference.md similarity index 100% rename from skills/using-unity/references/2d-pixel-perfect/references/api-reference.md rename to skills/using-unity/references/configure-2d-pixel-perfect/references/api-reference.md diff --git a/skills/using-unity/references/2d-pixel-perfect/references/camera-setup-builtin.cs b/skills/using-unity/references/configure-2d-pixel-perfect/references/camera-setup-builtin.cs similarity index 100% rename from skills/using-unity/references/2d-pixel-perfect/references/camera-setup-builtin.cs rename to skills/using-unity/references/configure-2d-pixel-perfect/references/camera-setup-builtin.cs diff --git a/skills/using-unity/references/2d-pixel-perfect/references/camera-setup-urp.cs b/skills/using-unity/references/configure-2d-pixel-perfect/references/camera-setup-urp.cs similarity index 100% rename from skills/using-unity/references/2d-pixel-perfect/references/camera-setup-urp.cs rename to skills/using-unity/references/configure-2d-pixel-perfect/references/camera-setup-urp.cs diff --git a/skills/using-unity/references/2d-pixel-perfect/references/pipeline-detection.cs b/skills/using-unity/references/configure-2d-pixel-perfect/references/pipeline-detection.cs similarity index 100% rename from skills/using-unity/references/2d-pixel-perfect/references/pipeline-detection.cs rename to skills/using-unity/references/configure-2d-pixel-perfect/references/pipeline-detection.cs diff --git a/skills/using-unity/references/2d-pixel-perfect/references/sprite-settings.cs b/skills/using-unity/references/configure-2d-pixel-perfect/references/sprite-settings.cs similarity index 100% rename from skills/using-unity/references/2d-pixel-perfect/references/sprite-settings.cs rename to skills/using-unity/references/configure-2d-pixel-perfect/references/sprite-settings.cs diff --git a/skills/using-unity/references/craft-game-floors/craft-game-floors.md b/skills/using-unity/references/craft-game-floors/craft-game-floors.md index 9e59164..61c6f0b 100644 --- a/skills/using-unity/references/craft-game-floors/craft-game-floors.md +++ b/skills/using-unity/references/craft-game-floors/craft-game-floors.md @@ -92,10 +92,10 @@ applying 3D instructions. The scorecard's 2D anchor set still applies. This skill owns **opinionated creation and floors** — which values, in what order, to what bar. Catalog neighbours own **mechanics on existing setups**: volume/post mechanics → -`urp-postprocessing` · routing sources into existing mixer groups → `audio-setup-mixers` · audio -import/memory → `optimize-audio` · UI framework choice and construction → `ui` · font assets → +`urp-postprocessing` · routing sources into existing mixer groups → `route-audio-to-mixer-groups` · audio +import/memory → `optimize-audio` · UI framework choice and construction → `create-ui` · font assets → `optimize-text-mesh-pro` · backend services → `build-live-game` · pixel-perfect 2D → -`2d-pixel-perfect`. When an ask is purely mechanical, route there; when it's "make it good," it's +`configure-2d-pixel-perfect`. When an ask is purely mechanical, route there; when it's "make it good," it's this skill, which then delegates the mechanics. If this index wants to grow, the new thing is a catalog skill routed by the prompt, not another floor — a floor must apply to *every* game. diff --git a/skills/using-unity/references/craft-game-floors/references/camera-rigs.md b/skills/using-unity/references/craft-game-floors/references/camera-rigs.md index b37208c..7ac7567 100644 --- a/skills/using-unity/references/craft-game-floors/references/camera-rigs.md +++ b/skills/using-unity/references/craft-game-floors/references/camera-rigs.md @@ -27,7 +27,7 @@ The camera is half of game feel and the first thing a hand-rolled implementation ## 2D follow -`CinemachineCamera` + **Position Composer**: dead zone ~0.1×0.1 (breathing room for small motion), look-ahead 0.5–1 s along velocity, damping asymmetric (loose horizontal, tight vertical for platformers). Pixel-art projects: pair with `2d-pixel-perfect`. +`CinemachineCamera` + **Position Composer**: dead zone ~0.1×0.1 (breathing room for small motion), look-ahead 0.5–1 s along velocity, damping asymmetric (loose horizontal, tight vertical for platformers). Pixel-art projects: pair with `configure-2d-pixel-perfect`. ## Feel hooks diff --git a/skills/using-unity/references/craft-game-floors/references/game-audio.md b/skills/using-unity/references/craft-game-floors/references/game-audio.md index b2a6ff6..309fab2 100644 --- a/skills/using-unity/references/craft-game-floors/references/game-audio.md +++ b/skills/using-unity/references/craft-game-floors/references/game-audio.md @@ -1,6 +1,6 @@ # Game Audio -> Craft reference for the `craft-game-floors` skill. Relative links in this file resolve to the skill directory. **Load:** during the feel pass, or whenever a game has zero or unrouted audio. Routing sources into *existing* mixer groups lives in `audio-setup-mixers`; import/memory settings in `optimize-audio`; everything else about the mixer is owned here. Confirm engine behavior against the linked documentation for the installed version before acting on it. +> Craft reference for the `craft-game-floors` skill. Relative links in this file resolve to the skill directory. **Load:** during the feel pass, or whenever a game has zero or unrouted audio. Routing sources into *existing* mixer groups lives in `route-audio-to-mixer-groups`; import/memory settings in `optimize-audio`; everything else about the mixer is owned here. Confirm engine behavior against the linked documentation for the installed version before acting on it. ## The floor rule @@ -21,7 +21,7 @@ Always apply a 5 ms fade-in/out envelope to every clip — raw edges click. One AudioMixer: `Master → Music, SFX, Ambient`. Every AudioSource routes to a group — nothing on Master directly. -- **Creation is editor-UI work** in the [Audio Mixer window](https://docs.unity.com/en-us/engine//manual/audio/mixer/overview.md) — there is no public scripting API for creating mixers or groups; the mechanics live under that manual section. Once the groups exist, `audio-setup-mixers` routes every source into the right one — that skill *routes only*: it does not create mixers or groups, set volumes, expose parameters, or configure ducking. Those are this file's recipes. +- **Creation is editor-UI work** in the [Audio Mixer window](https://docs.unity.com/en-us/engine//manual/audio/mixer/overview.md) — there is no public scripting API for creating mixers or groups; the mechanics live under that manual section. Once the groups exist, `route-audio-to-mixer-groups` routes every source into the right one — that skill *routes only*: it does not create mixers or groups, set volumes, expose parameters, or configure ducking. Those are this file's recipes. - **Exposed parameters.** Expose each group's Volume to script (mechanics on the Audio Mixer manual page above) and name the parameters **MusicVol** and **SFXVol** — the shell's settings sliders bind to these names. Set from script with [`mixer.SetFloat("MusicVol", dB)`](https://docs.unity.com/en-us/engine//script-reference/unityengine/audio/audiomixer/setfloat.md) — its call-timing constraint and its snapshot interaction are documented on that page; the ducking rule below exists because of that interaction. - **Ducking — never through the parameter the sliders own.** Once a settings slider calls `SetFloat("MusicVol", …)`, snapshots stop controlling that parameter, so snapshot ducking of the diff --git a/skills/using-unity/references/craft-game-floors/references/game-shell.md b/skills/using-unity/references/craft-game-floors/references/game-shell.md index 9685fbc..989a3a4 100644 --- a/skills/using-unity/references/craft-game-floors/references/game-shell.md +++ b/skills/using-unity/references/craft-game-floors/references/game-shell.md @@ -1,6 +1,6 @@ # Game Shell -> Craft reference for the `craft-game-floors` skill. **Load:** once the core loop works, before the feel pass concludes — and in any ad-hoc session, whenever the game boots straight into gameplay: such a build isn't done. UI construction mechanics live in the `ui` skill family; this reference owns which screens exist and how they behave. Relative links in this file resolve to the skill directory. Confirm engine behavior against the linked documentation for the installed version before acting on it. +> Craft reference for the `craft-game-floors` skill. **Load:** once the core loop works, before the feel pass concludes — and in any ad-hoc session, whenever the game boots straight into gameplay: such a build isn't done. UI construction mechanics live in the `create-ui` skill; this reference owns which screens exist and how they behave. Relative links in this file resolve to the skill directory. Confirm engine behavior against the linked documentation for the installed version before acting on it. ## The opinion diff --git a/skills/using-unity/references/create-2d-physics/create-2d-physics.md b/skills/using-unity/references/create-2d-physics/create-2d-physics.md index 20d5a67..6975cc9 100644 --- a/skills/using-unity/references/create-2d-physics/create-2d-physics.md +++ b/skills/using-unity/references/create-2d-physics/create-2d-physics.md @@ -114,7 +114,7 @@ Prefer in order: the C# example on the type or member page you are using; existi Physics changes alter runtime behaviour, so a clean compile isn't enough. Run these checks in order. If any check fails, reread the [docs pages](#full-topic-map) to find out what you missed, fix it, and run the checks again. -1. Use `console_status` to check the project has zero console errors. +1. Use `console status` to check the project has zero console errors. 2. Read back what you changed, because a change can compile cleanly and still do nothing: - For components you added or configured in the scene, use `script eval` to check each one exists on its GameObject and its properties hold the values you set, such as a Collider 2D's `isTrigger` or the members listed on a Core component's type page. - For a script, read it back and check it uses the system and namespace from [Step 0](#step-0-which-physics-system), and sets each Core body's `type` explicitly. diff --git a/skills/using-unity/references/create-tile-palette-or-rule-tiles/SECURITY.md b/skills/using-unity/references/create-tile-palette-or-rule-tiles/SECURITY.md new file mode 100644 index 0000000..9ee25dd --- /dev/null +++ b/skills/using-unity/references/create-tile-palette-or-rule-tiles/SECURITY.md @@ -0,0 +1,15 @@ +# Security notes: create-tile-palette-or-rule-tiles + +This skill can have the agent run C# in the user's live Unity Editor with `unity command script eval`, to read project and Play mode state while it creates or checks tile palettes and rule tiles. Automated skill scanners flag running code in the Editor as a powerful capability. It is intentional, and it is limited by the safeguards below. + +## Accepted risks + +| Risk | Capability | Why it is accepted | +|---|---|---| +| `SEC_POWER_CAP` | Runs C# in the user's live Editor through `unity command script eval` | It only reaches the Editor the user already has open, on their own machine, as that user, so it grants nothing they couldn't do themselves. | + +## Mitigations + +- **Only the user's own Editor.** The code runs in the Editor open on this machine. It can't reach another machine or another user's Editor. +- **Nothing left behind.** The skill tells the agent never to leave verification code in the user's scripts, and to create a restore point before changes. +- **No remote code.** Nothing downloaded from outside is executed. diff --git a/skills/using-unity/references/create-tile-palette-or-rule-tiles/create-tile-palette-or-rule-tiles.md b/skills/using-unity/references/create-tile-palette-or-rule-tiles/create-tile-palette-or-rule-tiles.md index cdb069c..42a56a3 100644 --- a/skills/using-unity/references/create-tile-palette-or-rule-tiles/create-tile-palette-or-rule-tiles.md +++ b/skills/using-unity/references/create-tile-palette-or-rule-tiles/create-tile-palette-or-rule-tiles.md @@ -75,13 +75,13 @@ Pick the matching reference doc based on what the user wants, then follow it: Do the following checks: -1. Check the project has zero console errors. Use `console_status` for counts. -2. Read the assets back with `eval` (fully qualified), because an asset can exist without its settings having stuck: +1. Check the project has zero console errors. Use `console status` for counts. +2. Read the assets back with `script eval` (fully qualified), because an asset can exist without its settings having stuck: - If you created a tile palette, check that `AssetDatabase.LoadAllAssetsAtPath` on the palette returns a `GridPalette` sub-asset, and that the `Grid` on the palette's root GameObject has the `cellLayout` and `cellSize` you chose. - If you created a RuleTile, check that `AssetDatabase.LoadAssetAtPath` with the RuleTile type you created returns the asset, that `m_TilingRules.Count` equals the number of rules you created, and that each rule's `m_Sprites` has exactly one entry: `null` for an empty RuleTile, or the assigned sprite for one built from sprites. 3. If you built a RuleTile from sprites, check that it picks the right sprite as it's painted, because correct fields don't prove the rules match the art. Open a temporary scene with `EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Additive)`, add a Grid with a Tilemap, use `Tilemap.SetTile` to paint a 3x3 block of the RuleTile, and check that `Tilemap.GetSprite` at each cell returns the sprite of the rule that matches that cell's neighbours. For example, the centre cell gets the fully surrounded rule's sprite, if the RuleTile has that rule. Then close the scene with `EditorSceneManager.CloseScene(scene, true)` without saving it. 4. If a value doesn't match, fix the asset and repeat the check. -5. Stop there unless the user asked you to prove it works or you suspect a specific fault. If you do enter Play mode, do it once only to chase a fault you already suspect. Read the world through `eval` rather than adding logging. Take no screenshots, because they take too much time. +5. Stop there unless the user asked you to prove it works or you suspect a specific fault. If you do enter Play mode, do it once only to chase a fault you already suspect. Read the world through `script eval` rather than adding logging. Take no screenshots, because they take too much time. If a check fails, go back and reread the [docs pages](#full-topic-map) to find out what you missed. diff --git a/skills/using-unity/references/create-ui/SECURITY.md b/skills/using-unity/references/create-ui/SECURITY.md new file mode 100644 index 0000000..626172f --- /dev/null +++ b/skills/using-unity/references/create-ui/SECURITY.md @@ -0,0 +1,18 @@ +# Security notes: create-ui + +This skill has the agent run C# inside the user's open Unity Editor through `unity command script eval`, to set up scenes and Panel Settings, set UI states, and read styles and layout. Automated skill scanners flag that as a powerful capability. It is intentional, and it is limited by the safeguards below. + +## Accepted risks + +| Risk | Capability | Why it is accepted | +|---|---|---| +| `SEC_POWER_CAP` | Runs C# in the user's open Editor through `unity command script eval`, and runs a test script the agent writes that calls `unity command` | It only reaches the Editor the user already has open, on their own machine, as that user, so it grants nothing they couldn't do themselves. `script eval` sits behind the Pipeline capability gate. No code fetched from a remote source is run. Where a named `unity command` covers a step, the skill uses that instead of `script eval`. | + +## Mitigations + +- **Local Editor only.** `unity command script eval` talks to the Editor open on this machine. It can't reach another machine or another user's Editor. +- **Capability gate.** `script eval` is only available when the project's Pipeline package provides it. +- **No remote code.** The agent runs C# it writes from this skill's own guides. Nothing downloaded from outside is executed. +- **Named commands first.** Compiling, entering Play mode, capturing the Game view, installing a package, and running tests use their dedicated `unity command` instead of `script eval`. +- **Scripts stay out of the project.** The C# files and the test script the agent runs are written to `Temp/`, not `Assets/`, so they aren't imported into the project or shipped in a build. +- **One package, from the Editor.** The only package the skill adds is the UI Test Framework, without a version, so Package Manager uses the one that ships with the Editor and nothing is downloaded. The final report names it so the user can remove it. diff --git a/skills/using-unity/references/create-ui/create-ui.md b/skills/using-unity/references/create-ui/create-ui.md new file mode 100644 index 0000000..3511538 --- /dev/null +++ b/skills/using-unity/references/create-ui/create-ui.md @@ -0,0 +1,150 @@ +--- +name: create-ui +description: "Creates, edits, and explains Unity game and editor UI in UI Toolkit, uGUI, or IMGUI, matching the framework the project already uses. Use when the user wants a menu, HUD, or editor window built, changed, styled, or explained." +--- + +# Create and edit Unity UI + +Build, change, and explain UI with whichever of Unity's three UI frameworks fits the project, and deliver new UI as a working demo that you have run and reviewed. + +This skill works best with the Unity CLI driving an open Editor (the `unity-cli` skill), the workflow it was built and tested with: compiling, reading the Console, entering Play mode, running tests, and capturing the Game view from the command line. Without it, the build and review steps need the user to do those in the Editor. + +## Important + +- Prefer `WebFetch` over `WebSearch` — faster and lands on the exact reference. Only fetch what you need. Replace `` with the following before fetching: + - **docs.unity.com**: The Unity version, eg `6000.7`. Read it from `ProjectSettings/ProjectVersion.txt` and keep the major and minor parts only. The guides link the `.md` form of each page, which is shorter to read than the HTML page. + - **Package docs**: if the project has the package's docs at `Library/PackageCache/@*/Documentation~/`, read those `.md` files instead of fetching, as the uGUI guide does. +- Before you go forward with a workflow or diagnosis, open and read the doc pages that the framework guide says to read for what you're about to build, and name the pages you read in your reply. Fetch other pages only for a feature you use that the guide doesn't cover. This is because your training knowledge about Unity might be out of date, incorrect, or for the wrong Unity version. +- Create a restore point you can roll back to if your changes fail, because UI changes touch scenes, assets, and scripts at once: copy the scene and any files you'll change into `Temp/restore/` in the project. Unity doesn't import `Temp/`, and nothing outside the project changes. +- Do only what's asked. Don't change unrelated assets or files. Avoid long explanations. A request to create UI asks for the deliverables in Step 4, so build all of them. +- Never leave verification code in the user's script. Never build logging or detection into their scripts that they didn't ask for; the mock HUD test's `[UI check]` log line is part of the test, not of their scripts. To check behaviour in Play mode, read the values you need through `script eval`, as the framework guide's Checks section describes. +- Use the Unity CLI to compile, read the Console, enter Play mode, and capture the Game view. For UI Toolkit, the guide lists the commands and flags a UI build needs, so load the `unity-cli` skill only if one of them fails; for uGUI and IMGUI, use the `unity-cli` skill. If the CLI can't reach the Editor, ask the user to focus the Unity Editor and tell you what the Console shows, because the Editor only imports and compiles new files when it's focused or told to recompile. + +## Glossary + +| Term | Meaning | +|---|---| +| UI Toolkit (UITK, UIElements) | UI built from UXML files (structure) and USS files (styles), for runtime and Editor UI | +| uGUI (Unity UI, Canvas UI) | UI built from GameObjects with RectTransforms under a Canvas, from the `com.unity.ugui` package | +| IMGUI (immediate mode GUI) | UI drawn from code every frame in `OnGUI()`, used for older Editor tools and debug overlays | +| "legacy UI" | Usually uGUI. If the user points at `OnGUI` code, they mean IMGUI. | +| Panel Renderer, UI Document | Components that show a UXML file in a scene. New UI uses Panel Renderer; UI Document isn't the default for new UI, but existing scenes may use it. | +| Panel Settings | The asset that controls how a UI Toolkit panel renders and scales | +| Theme Style Sheet (TSS) | Default styles for the built-in UI Toolkit controls, assigned on the Panel Settings | +| TextMesh Pro (TMP) | uGUI's text components and font assets. UI Toolkit uses its own TextCore font assets. | +| Controller script | The MonoBehaviour this skill adds to feed live values to the UI and handle its input | + +## Step 1: Get the project context + +1. Read `ProjectSettings/ProjectVersion.txt`. Its major and minor version is ``. If it's older than 6000.7, tell the user this skill is written for Unity 6000.7 and later, and ask before you continue. +2. Read `Packages/manifest.json`. `com.unity.ugui` provides uGUI and TextMesh Pro, and `com.unity.inputsystem` decides which input module uGUI needs. +3. Read `activeInputHandler` in `ProjectSettings/ProjectSettings.asset`: 0 is the old Input Manager, 1 is the Input System package, and 2 is both. +4. Check whether the Unity CLI reaches an open Editor for this project. If it does, note the `cursor` that `console status` returns, so you can later read only the Console entries logged after you started. Never run `console clear`, because it also deletes the user's own entries, including errors they may want fixed. + +## Step 2: Pick the framework + +1. If the request names a framework, a file type, or a component from this table, use that framework, because the user's choice overrides what the project uses elsewhere. + + | Request mentions | Framework | + |---|---| + | `.uxml` or `.uss` files, "UI Toolkit", "UITK", "UIElements", `CreateGUI`, Panel Renderer, UI Document | UI Toolkit | + | "uGUI", "Canvas", "RectTransform", a UI `.prefab`, "legacy UI" (unless it points at `OnGUI` code) | uGUI | + | "IMGUI", `OnGUI`, `OnInspectorGUI`, "immediate mode" | IMGUI | + +2. Otherwise, search the project and use the framework it already uses for the same kind of UI (runtime or Editor), because a second framework for the same kind of UI doubles the styling and input setup. + + | Look for | Indicates | + |---|---| + | `.uxml` or `.uss` files outside `Editor` folders, Panel Renderer or UI Document components in scenes | UI Toolkit, runtime | + | `.uxml` files in `Editor` folders, editor scripts with `CreateGUI()` | UI Toolkit, Editor | + | `Canvas` components in scenes or prefabs | uGUI | + | Editor scripts with `OnGUI()` or `OnInspectorGUI()` | IMGUI | + +3. If the project has no runtime UI yet and the request names no framework, provide pros and cons for each framework given the current task and let the user decide. +4. If the request is for Editor UI and the project has no Editor UI pattern, use UI Toolkit, because Unity recommends it for new Editor UI. Use IMGUI only when the code you're changing already uses it or the user asks for it. +5. If the request is a comparison question ("Which one should I use for mobile?"), answer it directly without changing files. Use the feature differences on the [UI system comparison](https://docs.unity.com/en-us/engine//manual/uitoolkits/ui-system-compare.md) page and relate them to the user's project. +6. If the user shares a Figma link, say this skill can't import Figma designs, and ask for a description or a screenshot of the screen. Then continue with Step 3. + +## Step 3: Read the guide + +Read the guide for the framework, then the doc pages it lists for what you're building: + +| Framework | Guide | +|---|---| +| UI Toolkit | [UI Toolkit guide](references/uitk-skill.md) | +| uGUI | [references/ugui-skill.md](references/ugui-skill.md) | +| IMGUI | [references/imgui-skill.md](references/imgui-skill.md) | + +The guides send you to these files when you need them: + +- [references/ui-visual-design.md](references/ui-visual-design.md): palette, type, spacing, states, and how to review a capture. Read it for any new UI. +- [references/uitk-pointermanipulator-guide.md](references/uitk-pointermanipulator-guide.md): drag and drop for UI Toolkit inventories and crafting screens. +- [references/uitk-painter2d.md](references/uitk-painter2d.md): rings, charts, and custom shapes in UI Toolkit. +- [references/uitk-svg-icons.md](references/uitk-svg-icons.md): SVG icons for UI Toolkit. +- [references/uitk-testing.md](references/uitk-testing.md): the mock HUD test that drives a UI Toolkit screen through its states, checks its interactions, and captures each state, and Edit Mode tests for reusable controls. +- [references/ugui-scrollview-setup.md](references/ugui-scrollview-setup.md): uGUI scroll views. + +## Step 4: Do the work + +- **Question about existing UI:** inspect the files, scene, or prefab and answer. Don't change files. +- **Targeted edit:** change what the request covers, and keep the rest of each file as it was. +- **New UI:** build it in two phases, so the UI works before you spend time on its look. + + **Phase 1: function.** Make the UI work, and prove it. + 1. **Files:** create the files the guide lists for a screen, with plain styles. Define colors, sizes, and spacing once (USS custom properties in UI Toolkit), so phase 2 can restyle the screen in one place. + 2. **Scene:** for runtime UI, add the UI to the open scene. If the open scene is untitled, first save it under `Assets/Scenes/` with a name that describes the UI, using an explicit path. Editor UI (windows, Inspectors) needs no scene. + 3. **Controller script:** make values change, interactions respond, and screens switch, unless the user asks for a static layout. Give every state a public method, and keep demo gameplay that changes values in a separate script, so tests can drive the UI on their own. + 4. **Tests and a quick visual check:** for UI Toolkit, follow the guide's phase 1 checks: a mock HUD test that sets each state through the controller, checks the interactions, asserts the layout, and captures each state, over dark and light backgrounds for a HUD drawn over the game and a dark one for a screen that covers it ([references/uitk-testing.md](references/uitk-testing.md)). Write Edit Mode tests only for a reusable custom control. A screen with one or two states and no interactions (a compass, a timer) skips the test framework: set its states in Play mode and capture the Game view. For uGUI, enter Play mode and read the sizes the guide's Checks section lists through `script eval`. Fix anything missing, clipped, overlapping, or unreadable before moving on. + + **Phase 2: theme and quality.** Make it look like it belongs in the game. + 1. **Theme:** apply the tips in `references/ui-visual-design.md`: a direction that fits the game, the palette, type scale, spacing, depth, interactive states, motion, and SVG icons for clarity. + 2. **Review:** do at least two review passes. One pass is a theme change, then a fresh mock HUD test run (UI Toolkit) or a fresh Game view capture in Play mode (uGUI), then the design guide's review checklist on the new captures. Fix the most visible problem in the next pass. Captures from before a change, phase 1's quick check, and the in-context capture below don't count as passes, because only a fresh capture shows whether the change worked. For Editor UI, review a fresh capture of the open window instead (`capture editor_window`). + 3. **In context:** capture the Game view in Play mode once, to see the UI over the real scene. For UI Toolkit, use the one-command capture script in the testing reference; if Play mode doesn't advance past frame 1 after a second try, skip the capture and say so in the final report. + 4. **Before the final step:** for new UI, check that this phase had at least two review passes, each with fresh captures after a change. If it had fewer, do the missing passes now. + +## Final step + +Do the following checks: + +1. Check that `console status` reports no compile failure, and that `console get --since --level error`, from the cursor you noted in Step 1, returns no errors your changes caused. Errors that were already in the Console before you started are the user's: name them in the final report instead of fixing them. +2. Stop there unless the user asked for proof or a specific fault is suspected, because phase 1's tests and phase 2's review passes already checked the UI. +3. If a specific fault is suspected, enter Play mode only once to chase it. Read the world through `script eval` (an element's `resolvedStyle` or `layout`, a `RectTransform.rect.size`) rather than adding logging, and take no screenshots. + +If a check fails, go back and reread the doc pages for that feature, listed in the guide's docs table, to find out what you missed. Then fix the files and run the checks again. + +## Final report + +A short checklist: + +- The framework you used, and why (named by the user, detected, or chosen). +- The files you created or changed, and the scene, with their paths as saved on disk. +- The doc pages you read. +- The tests you wrote, their results, and the capture folder. +- Any package you added, such as the UI Test Framework, so the user can remove it. +- Each phase 2 review pass: what you changed, and what the fresh captures showed. +- What the in-context capture showed, and any fault you chased in the final step. +- Anything left for the user, such as sound hooks to attach or values to tune. + +## Worked example + +Request: "Create a HUD with a health bar and an ammo counter." The project has no UI. + +1. Step 1: `ProjectVersion.txt` says `6000.7.0b3`, so `` is `6000.7`. The project uses the Input System package only. The CLI reaches the Editor, and `console status` returns the cursor to read from later. +2. Step 2: the project has no `.uxml`, `.uss`, or Canvas, and the request names no framework, so give the pros and cons of UI Toolkit and uGUI for this HUD and let the user decide. The user picks UI Toolkit, so note that for the final report. +3. Step 3: read `references/uitk-skill.md`, then the Panel Renderer, USS properties reference, and USS transitions pages for `6000.7`. +4. Step 4, phase 1: create `Assets/UI/HUD/HUD.uxml`, `HUD.uss` (plain styles, colors and sizes as custom properties), and `HUDController.cs`. Reuse `Assets/UI/PanelSettings.asset`, and add a Panel Renderer to a `HUD` GameObject in the open scene, `Assets/Scenes/Main.unity`. Enable the UI Test Framework, and write `Assets/UI/HUD/Tests/HUDStates.cs` for four states (default, low health, empty magazine, kill) over dark and light backgrounds. The quick check shows every element laid out and nothing clipped. +5. Step 4, phase 2: choose a direction for the game, restyle through the custom properties, and draw SVG icons for health and ammo, then run the test again (pass 1). The fresh captures show the ammo count hard to read on the light background, so add a backing panel and run the test again (pass 2). Capture the Game view once over `Main.unity`. +6. Final step: `console status` reports no compile failure, `console get` since the Step 1 cursor shows no errors, and no fault is suspected, so stop. +7. Final report: + + ``` + - Framework: UI Toolkit (project had no UI; the user chose it after the pros and cons) + - Files: Assets/UI/HUD/HUD.uxml, Assets/UI/HUD/HUD.uss, Assets/UI/HUD/HUDController.cs + - Scene: Assets/Scenes/Main.unity (HUD GameObject with a Panel Renderer) + - Docs read: Panel Renderer component, USS properties reference, USS transitions + - Tests: Assets/UI/HUD/Tests/HUDStates.cs passes; 8 captures in Temp/UIStates/ + - Review pass 1: restyled the panels and added SVG icons; fresh captures showed the ammo count unreadable on the light background + - Review pass 2: added a backing panel behind the ammo count; fresh captures read on both backgrounds + - Added: com.unity.ui.test-framework (ships with the Editor; remove it in Package Manager if you don't want it) + - For you: HUDController.SetHealth(int) and SetAmmo(int, int) take your gameplay values + ``` diff --git a/skills/using-unity/references/create-ui/references/imgui-skill.md b/skills/using-unity/references/create-ui/references/imgui-skill.md new file mode 100644 index 0000000..34c057a --- /dev/null +++ b/skills/using-unity/references/create-ui/references/imgui-skill.md @@ -0,0 +1,64 @@ +# IMGUI guide + +Maintain and extend IMGUI (immediate mode) code: EditorWindows and custom Inspectors that draw in `OnGUI()` or `OnInspectorGUI()`, PropertyDrawers that draw in `OnGUI(Rect, SerializedProperty, GUIContent)`, and runtime debug overlays in `MonoBehaviour.OnGUI()`. + +Use this guide when the code you're changing already uses IMGUI, the user asks for IMGUI, or the project's editor tools use IMGUI exclusively. New editor windows and Inspectors in other projects use UI Toolkit, because it's Unity's recommended system for new Editor UI. IMGUI isn't for runtime game UI; use UI Toolkit or uGUI for that. + +## Contents + +- Docs to read first +- Conventions +- Rules +- Console errors +- Checks + +## Docs to read first + +Replace `` in these URLs with the project's Editor version, for example `6000.7`. Open the page for what you're building before writing code, because it has the current structure, a complete example, and the rules for styles, serialized data, undo, and layout: + +| Building | Read | +|---|---| +| EditorWindow | [Editor Windows](https://docs.unity.com/en-us/engine//manual/uitoolkits/ui-imgui/extending-the-editor/editor-editor-windows.md) | +| Custom Inspector | [Custom Editors](https://docs.unity.com/en-us/engine//manual/uitoolkits/ui-imgui/extending-the-editor/editor-custom-editors.md) | +| PropertyDrawer | [Property Drawers](https://docs.unity.com/en-us/engine//manual/uitoolkits/ui-imgui/extending-the-editor/editor-property-drawers.md) | +| Controls (buttons, fields, sliders) | [IMGUI controls](https://docs.unity.com/en-us/engine//manual/uitoolkits/ui-imgui/gui-controls.md) | +| Layout (horizontal, vertical, scroll, areas) | [IMGUI layout modes](https://docs.unity.com/en-us/engine//manual/uitoolkits/ui-imgui/gui-layout.md) | +| Styles and skins | [Customization](https://docs.unity.com/en-us/engine//manual/uitoolkits/ui-imgui/gui-customization.md) | + +## Conventions + +Follow the project's existing editor scripts first. Otherwise: + +| Type | Convention | Example | +|------|------------|---------| +| Script names | PascalCase | `MyToolWindow.cs` | +| EditorWindow | `[Name]Window.cs` | `LevelEditorWindow.cs` | +| Custom Editor | `[Type]Editor.cs` | `EnemyEditor.cs` | +| PropertyDrawer | `[Type]Drawer.cs` | `RangeDrawer.cs` | + +**Location:** put scripts that use `UnityEditor` in an `Editor` folder or an Editor-only assembly definition, because player builds can't compile `UnityEditor` code. Keep runtime debug overlays (`MonoBehaviour.OnGUI`) out of Editor folders, because they must run in the player. + +## Rules + +The doc pages cover the general rules. These are the ones that cause the errors in the next table, or that the pages don't spell out: + +- **Styles:** create each `GUIStyle` lazily on the first `OnGUI` call and cache it, because `EditorStyles` and `GUI.skin` aren't ready earlier. +- **PropertyDrawers:** edit the `SerializedProperty` that `OnGUI` receives, and don't call `Update()` or `ApplyModifiedProperties()` from the drawer, because that can discard changes the Inspector hasn't applied yet. +- **Begin/End pairs:** close every `Begin*` call on every code path, including early returns, or use the `using (new EditorGUILayout.HorizontalScope())` forms. +- **Same controls per event:** draw the same controls during the Layout and Repaint events of one frame. Change conditions that add or remove controls outside `OnGUI`, or at the start of the Layout event. + +## Console errors + +| Console message | Cause | Fix | +|---|---|---| +| `EndLayoutGroup: BeginLayoutGroup must be called first.` | An `End*` call without its `Begin*`, often after an early return | Match the pairs on every path, or use the `Scope` forms | +| `GUI Error: You are pushing more GUIClips than you are popping. Make sure they are balanced.` | A `BeginScrollView`, `BeginArea`, or `BeginClip` without its `End*` | Close every scope | +| `ArgumentException: Getting control 1's position in a group with only 1 controls when doing repaint` | Controls drawn in Layout differ from those drawn in Repaint | Apply the "same controls per event" rule | + +## Checks + +1. The Console has no errors after the scripts compile. +2. Open the window or select an object that uses the Inspector, and check that the Console stays free of the errors in the table above. +3. For runtime overlays, enter Play mode, check through `script eval` that the component that draws the overlay is active and enabled, and check that the Console stays free of errors. Don't add logging to the script. + +If a check fails, reread the doc page for that script type before changing the code again. diff --git a/skills/using-unity/references/create-ui/references/ugui-scrollview-setup.md b/skills/using-unity/references/create-ui/references/ugui-scrollview-setup.md new file mode 100644 index 0000000..1262eb5 --- /dev/null +++ b/skills/using-unity/references/create-ui/references/ugui-scrollview-setup.md @@ -0,0 +1,24 @@ +# uGUI ScrollView setup + +Read `Library/PackageCache/com.unity.ugui@*/Documentation~/script-ScrollRect.md` first. The path resolves to the Unity project folder. Build this hierarchy, because it's the one where a missing or misordered part is easiest to spot when items duplicate, jitter, or don't scroll: + +``` +ScrollView (ScrollRect) +├── Viewport (RectTransform + Image + Mask, or RectTransform + Image + RectMask2D) +│ └── Content (RectTransform + VerticalLayoutGroup + ContentSizeFitter) +│ └── [Children, static or added at runtime] +└── Scrollbar (optional) +``` + +- **ScrollRect** goes on the root object. Assign its Content and Viewport fields, and the Scrollbar if there is one. +- **Viewport** clips the content and receives the drag. Give it an Image, because the ScrollRect only gets drags over a raycast target. Add a RectMask2D for rectangular viewports, because it's cheaper than a Mask and lets the Image be fully transparent. Use a Mask only for non-rectangular shapes; it clips to the Image's shape, so keep the Image visible to the Mask and turn off Show Mask Graphic to hide it. +- **Content** stretches across the top of the Viewport (anchors top-left to top-right, pivot y = 1), so it grows downward. It has a ContentSizeFitter with Vertical Fit set to Preferred Size on the same object as its VerticalLayoutGroup, so the scroll area grows with its children. +- **Dynamic items:** destroy the existing children of Content before adding new ones, because panels that repopulate on open otherwise add a second copy each time. + +| Symptom | Cause | Fix | +|---|---|---| +| Items duplicated each time the panel opens | Content isn't cleared before repopulating | Destroy Content's children before adding items | +| Content doesn't scroll | Content isn't taller than the Viewport, or the ScrollRect's Content field is empty | Add the ContentSizeFitter to Content, and assign the Content field | +| Dragging in empty space doesn't scroll | The Viewport has no Image to receive the drag | Add an Image to the Viewport | +| Items show outside the scroll area | The Viewport has no Mask or RectMask2D | Add one to the Viewport | +| Jitter or flicker | A ContentSizeFitter on an item whose parent layout group also sizes it | Remove the item's ContentSizeFitter, and size items with a Layout Element | diff --git a/skills/using-unity/references/create-ui/references/ugui-skill.md b/skills/using-unity/references/create-ui/references/ugui-skill.md new file mode 100644 index 0000000..15a1e1b --- /dev/null +++ b/skills/using-unity/references/create-ui/references/ugui-skill.md @@ -0,0 +1,121 @@ +# uGUI guide + +Understand existing uGUI (Canvas-based Unity UI), make targeted edits, and generate new Canvas hierarchies. + +Paths in this file that start with `references/`, such as `references/ugui-scrollview-setup.md`, resolve to the skill folder, not to this file's folder. Paths that start with `Library/` or `Assets/` resolve to the Unity project folder. + +## Contents + +- Docs to read first +- Critical rules +- Generation +- Canvas setup +- Layout +- RectTransform anchoring +- Text +- Interaction readiness +- Understanding and editing +- C# +- Error recovery +- Checks + +## Docs to read first + +The uGUI documentation ships with the package in the project: `Library/PackageCache/com.unity.ugui@*/Documentation~/`, where `@*` is the installed version's folder. Read only the `.md` files there. Open the page for what you're about to build before changing the hierarchy, because uGUI's layout components interact in ways that are easy to get wrong from memory. + +| Building | Read in `Documentation~/` | +|---|---| +| Canvas and render modes | `UICanvas.md` | +| Scaling to screen sizes | `HOWTO-UIMultiResolution.md`, `script-CanvasScaler.md` | +| Anchors and pivots | `UIBasicLayout.md`, `class-RectTransform.md` | +| Layout groups | `UIAutoLayout.md`, `script-HorizontalLayoutGroup.md`, `script-VerticalLayoutGroup.md`, `script-GridLayoutGroup.md` | +| Sizing to content | `HOWTO-UIFitContentSize.md`, `script-ContentSizeFitter.md`, `script-LayoutElement.md` | +| Scroll views | `script-ScrollRect.md`, then `references/ugui-scrollview-setup.md` | +| Input and events | `EventSystem.md`, `InputModules.md`, `script-GraphicRaycaster.md` | +| Text | `TextMeshPro/index.md` | +| Phone notches and cutouts | `script-SafeArea.md`, if present in the installed version | + +## Critical rules + +- **Fully qualified types:** write `UnityEngine.UI.Image` and `UnityEngine.UI.Button`, not `Image` and `Button`, because `UnityEngine.UIElements` and project namespaces have types with the same names, and the ambiguity breaks compilation. +- **Verify before modifying:** query the hierarchy before each change. Confirm that parents exist before adding children, and that components exist before setting their properties, because scripts that assume state fail partway and leave half-built UI. +- **Fix in place:** correct the specific broken property instead of destroying and recreating the hierarchy, because destroyed objects break every reference to them. If a fix fails, revert it before trying another. +- **One change at a time:** make one change, check the result, then make the next. Keep adjacent elements untouched when editing one. +- **Readable text:** text contrasts with its background, except for intentional low-contrast uses (disabled states, placeholder text, decoration). +- **Exact values:** apply pixel sizes, hex colors, positions, and spacing the user gives exactly. + +## Generation + +| Request | Output | +|---------|--------| +| A screen, menu, panel, or HUD | Canvas hierarchy (in the scene or a prefab) + a controller script for live values and interactions, in a saved scene | +| "Static layout" or "layout to wire up later" | Canvas hierarchy only | + +Steps: + +1. Search for existing Canvases, prefabs, sprites, and fonts, and use their actual paths. +2. Design the palette, type scale, spacing, and states before building (`references/ui-visual-design.md`). +3. If the open scene is untitled, save it with an explicit path, for example `EditorSceneManager.SaveScene(scene, "Assets/Scenes/MenuDemo.unity")`, because saving an untitled scene without a path opens a modal Save As dialog that blocks the Editor. +4. Build the Canvas (Canvas setup), then the content with anchors and layout groups. +5. Write the controller script, and wire each `Button.onClick`. +6. Save the scene, then run the checks at the end of this file. + +Name GameObjects in PascalCase (`SubmitButton`), and keep prefabs in feature folders (`Assets/UI/Inventory/`), unless the project uses other conventions. + +## Canvas setup + +`UICanvas.md` and `script-CanvasScaler.md` describe the render modes and scale modes. Defaults for a new Canvas: + +- **Scaler:** Scale With Screen Size, reference resolution 1920×1080 (or the project's standard), Match 0.5. +- **Existing Constant Pixel Size Canvas:** ask the user before changing it, because pixel-art and fixed-resolution projects use it on purpose. + +## Layout + +Read `UIAutoLayout.md` and `HOWTO-UIFitContentSize.md` before nesting layout groups or adding a Content Size Fitter. The mistake to avoid: a Content Size Fitter on a child of a layout group, where the group and the fitter both set the child's size. Put the fitter on the object that has the layout group instead, as ScrollView Content does. + +## RectTransform anchoring + +`UIBasicLayout.md` and `class-RectTransform.md` cover anchors and pivots. When placing an element from a description ("top right", "bottom bar"), set the anchors first, then the pivot to the same corner or edge, then position and size, because position values are relative to the anchors and the pivot. + +## Text + +- Use TextMesh Pro for all text, including world-space text, because legacy `Text` renders blurry when scaled. +- If `Assets/TextMesh Pro/` doesn't exist, import the TMP Essentials with `TMPro.TMP_PackageResourceImporter.ImportResources(true, false, false)` (essentials, no examples, not interactive). The Window > TextMeshPro menu item opens a modal dialog that blocks the Editor until a human dismisses it. + +## Interaction readiness + +Interactive UI fails silently without these: + +1. **One EventSystem** in the scene. +2. **The right input module:** if the project's Active Input Handling is the Input System package only, the EventSystem needs `InputSystemUIInputModule`, because `StandaloneInputModule` throws errors every frame without the old Input Manager. +3. **A GraphicRaycaster** on the Canvas. +4. **Raycast Target:** on for interactive graphics. Turn it off on decorative images and text, because a raycast target drawn over a button blocks its clicks unless it's the button's child, and every target adds raycast cost. + +## Understanding and editing + +Inspect the scene or prefab before answering or editing. + +- To explain structure: identify the Canvas and its render mode, map the parent-child relationships, say which layout groups control which children, and give the anchor setup. +- For "Why is this invisible?": check the size, anchors, parent bounds, sibling order, the Image's sprite or color alpha, and the CanvasGroup alpha. +- For edits: confirm the target exists, change the one property the request covers, and check the result. + +## C# + +- Use `[SerializeField]` fields for references, cache components in `Awake()`, and check serialized references for null before using them. +- Wire buttons in the controller script with `button.onClick.AddListener(...)`, so the wiring is in code you can read back and check. +- Place scripts next to their prefabs, unless the project keeps scripts elsewhere. + +## Error recovery + +1. Identify the exact error or symptom, and find its cause before changing anything. +2. Fix one issue at a time and check each fix. +3. If you're stuck, re-read the hierarchy and confirm your earlier changes were applied. Then consider whether the approach is wrong, rather than the implementation. + +## Checks + +1. The Console has no errors. +2. Enter Play mode, and through `script eval` call `Canvas.ForceUpdateCanvases()`, then read the `RectTransform.rect.size` of each key element, because layout groups only resize their children when the canvas updates. Check that every size is above zero. Don't add logging to the controller script. +3. The scene has exactly one EventSystem, with the input module that matches the project's input handling. +4. Capture the Game view and review it against `references/ui-visual-design.md`. Save Game view captures with `unity command capture game_view --source screen --output-path Temp/UIReview/.png`. The path is relative to the project folder, and Unity doesn't import `Temp/`. + +If a check fails, reread the page for that component from the table at the top before changing the hierarchy again. diff --git a/skills/using-unity/references/create-ui/references/ui-visual-design.md b/skills/using-unity/references/create-ui/references/ui-visual-design.md new file mode 100644 index 0000000..7acbed1 --- /dev/null +++ b/skills/using-unity/references/create-ui/references/ui-visual-design.md @@ -0,0 +1,62 @@ +# Visual Design for Game UI + +Read this before styling new UI, and again when reviewing captures. It applies to every framework; the notes in brackets name the UI Toolkit (USS) or uGUI way to do each thing. Paths such as `references/uitk-svg-icons.md` resolve to the skill folder. + +## Pick a direction first + +Choose a visual direction that fits the game's genre and tone, and state it in one sentence before writing any styles. Keep every element consistent with it. + +## Palette + +- A panel color family in 2–3 shades, one primary accent, semantic colors where the game needs them (health, mana, success, warning, rarity), and text colors for primary, secondary, and disabled text. +- Define colors once as tokens and reuse them [USS custom properties: `--accent: #F2B21E;` then `var(--accent)`; uGUI: a static color table in C#]. +- Contrast: body text at least 4.5:1 against its background, large numbers and headings at least 3:1. HUD text over the 3D world needs a backing panel, an outline, or a shadow [USS `text-shadow`, `-unity-text-outline-width`; TMP outline and underlay]. + +## Type scale + +- 4–5 sizes from a ratio, for example 14 / 18 / 24 / 32 / 48 px at a 1920×1080 reference: caption, body, label, heading, display. +- Big, bold numbers for values players read at a glance (health, ammo, timer, score); small letter-spaced captions above them [USS `letter-spacing`]. +- One or two weights: bold for values and headings, regular for descriptions. +- Nothing smaller than the caption size. Secondary text gets a dimmer color, not a smaller size. + +## Spacing and layout + +- A spacing scale such as 4 / 8 / 12 / 16 / 24 / 32 px, used for padding and margins everywhere. Each panel type gets one consistent inner padding. +- HUD elements sit in safe margins from the screen edges (24–40 px at 1080p) and align to shared edges and baselines. +- Size a full-screen menu (a skill tree, settings, an inventory) to fill most of the screen, about 70–85% of the reference width, so its content uses the type scale instead of shrinking to fit, and fill that space: enough rows or nodes to make it look like a real game's screen, or a side pane with details or a preview, rather than a half-empty panel. +- Group related information and separate groups with space before reaching for lines and borders. +- Visual hierarchy: the information players need most is the largest, brightest, and placed where they look (screen corners for HUDs, center for prompts). + +## Shapes and depth + +- One corner-radius family, and border widths that match the direction (1–2 px crisp, 4–6 px cartoon). +- Depth from layered panels, a darker bottom edge, inner highlights, and shadows [USS: `filter: drop-shadow(...)` or a nested element offset behind the panel; uGUI: a Shadow or Outline component or a sprite]. +- Give each distinct thing (a skill, an item, a menu category) its own icon, because shared icons make different things look interchangeable. +- Icons share one style (filled or stroked) and one size grid (16 / 24 / 32 / 48 px) [USS: SVG icons, see `references/uitk-svg-icons.md`; custom shapes with Painter2D, see `references/uitk-painter2d.md`]. + +## States and motion + +- Every interactive element has visibly different normal, hover, focus (keyboard and gamepad), pressed, and disabled states. Keep one clear selection highlight for controller navigation. +- Transitions of 100–250 ms for hover and press [USS `transition-property`, `transition-duration`, `transition-timing-function`; uGUI: Selectable color tint or animation]. +- Feedback for value changes: a pulse when health drops, a count-up for score, a pop when an item is picked up, a fade or slide when a panel opens [USS transitions on `scale`, `translate`, `opacity`, or `element.style` tweens from C#]. +- Add a placeholder binding for sound effects on button clicks or selections so users can easily attach sound to their UI. + +## Content and context + +- Believable sample data: real-sounding names, numbers, items, and quest text, so the screen reads as a real game. +- Show the UI in a context that sells it: a simple scene or backdrop behind a HUD, a title backdrop behind menus, a dimmed overlay behind modal panels. +- A small controller script makes the screenshot honest: values move, timers run, and states can be shown (for example a damaged health bar or a selected tab). + +## Reviewing a capture + +Capture the Game view in Play Mode at the reference resolution, then check, in order: + +1. **Hierarchy** — squint at the capture: does the most important information stand out first? +2. **Readability** — is every piece of text readable against what is behind it, and at least the caption size? +3. **Spacing and alignment** — do edges line up, are gaps consistent, are margins even? +4. **Defects** — anything clipped, overlapping, stretched, squashed, empty, or off-screen? +5. **Direction** — does it look like the chosen direction and genre throughout? +6. **Behavior** — do hover, press, and value changes show up (capture a second state if needed)? +7. **Colors** — does the color theory make sense here? Are they helping the intent of the UI element? + +Fix the most visible problem first, capture again, and repeat. Two or three passes usually take a screen from correct to polished. diff --git a/skills/using-unity/references/create-ui/references/uitk-painter2d.md b/skills/using-unity/references/create-ui/references/uitk-painter2d.md new file mode 100644 index 0000000..1a8c296 --- /dev/null +++ b/skills/using-unity/references/create-ui/references/uitk-painter2d.md @@ -0,0 +1,25 @@ +# Custom visuals with Painter2D + +Use Painter2D for what USS backgrounds can't draw: arcs and progress rings, pie and line charts, polygons, stars, badges, and wave patterns. For a rectangular gradient fill, use a USS `linear-gradient()` background first if the [Set background images](https://docs.unity.com/en-us/engine//manual/uitoolkits/uielements/uie-uss/properties/uib-styling-ui-backgrounds.md) page for `` lists it, because it needs no C#. + +Replace `` in these URLs with the project's Editor version, for example `6000.7`. Read the first page before writing the element, and the second for rings and arcs: + +- [Generate 2D visual content](https://docs.unity.com/en-us/engine//manual/uitoolkits/uielements/uie-ui-renderer/uie-generate-2d-visual-content.md): the `generateVisualContent` pattern and the Painter2D drawing model +- [Create a radial progress indicator](https://docs.unity.com/en-us/engine//manual/uitoolkits/uielements/uie-ui-renderer/uie-radial-progress-use-vector-api.md): a complete ring example +- [Painter2D](https://docs.unity.com/en-us/engine//script-reference/unityengine/uielements/painter2d.md) and [FillGradient](https://docs.unity.com/en-us/engine//script-reference/unityengine/uielements/fillgradient.md): member names and signatures + +## Names + +Painter2D uses the HTML Canvas 2D method names in PascalCase, but angles, arc direction, fill and stroke styles, line caps, and dashes take Unity types instead of Canvas values. Check each member in the Painter2D and FillGradient reference pages before writing it, because a Canvas name that looks right often doesn't compile. + +## Rules + +The pages above show the element pattern and repainting. These are the mistakes they don't warn about: + +- **Element type:** draw on a plain `VisualElement` subclass, not a built-in control, because built-in controls already generate their own content and yours layers with theirs. +- **Padding:** drawing starts at the element's top-left corner, not inside its padding. Offset every point by `contentRect.x` and `contentRect.y` to respect the USS padding. +- **Zero size:** return early when the width or height is below 1, because an element with no size yet gives arcs and gradients degenerate geometry. +- **Paths:** call `BeginPath()` before every path, or `Fill()` and `Stroke()` redraw the earlier sub-paths too. +- **Arc ends:** use `LineCap.Butt` for progress rings, because `Round` extends each end past its angle by half the line width. +- **Read-only callback:** change styles, add children, and call `MarkDirtyRepaint()` outside `generateVisualContent`, because doing it inside dirties the element again. +- **Expose settings:** mark the values designers tune (colors, thickness, progress) with `[UxmlAttribute]`. diff --git a/skills/using-unity/references/create-ui/references/uitk-pointermanipulator-guide.md b/skills/using-unity/references/create-ui/references/uitk-pointermanipulator-guide.md new file mode 100644 index 0000000..5cdb356 --- /dev/null +++ b/skills/using-unity/references/create-ui/references/uitk-pointermanipulator-guide.md @@ -0,0 +1,43 @@ +# Drag and drop with pointer manipulators + +Replace `` in these URLs with the project's Editor version, for example `6000.7`. Read them before writing a manipulator. They cover the `PointerManipulator` base class, attaching it with `AddManipulator`, pointer capture, and the PointerDown, PointerMove, PointerUp, and PointerCaptureOut lifecycle: + +- [Create a drag-and-drop UI](https://docs.unity.com/en-us/engine//manual/uitoolkits/uielements/uie-events/uie-event-examples/uie-create-drag-and-drop-ui.md) (an Editor window example; the manipulator works the same at runtime) +- [Move elements at runtime](https://docs.unity.com/en-us/engine//manual/uitoolkits/uielements/uie-support-for-runtime-ui/uie-runtime-examples/uie-move-elements-at-runtime.md) +- [Manipulators](https://docs.unity.com/en-us/engine//manual/uitoolkits/uielements/uie-events/uie-manipulators.md) +- [Capture the pointer](https://docs.unity.com/en-us/engine//manual/uitoolkits/uielements/uie-events/uie-capture-the-pointer.md) + +This file adds what inventory and crafting screens need on top of those pages. + +## Moving the dragged item + +1. On PointerDown, capture the pointer, store the pointer position, set `usageHints = UsageHints.DynamicTransform`, and call `BringToFront()` so the item draws above its siblings. +2. On PointerMove, set `style.translate = new Translate(delta.x, delta.y)`, where `delta` is the pointer movement since PointerDown. `translate` is an offset from the element's layout position in its parent's space, not a world position, and changing it skips the layout pass, so the other slots stay still. +3. If the item must draw above other slots (other parents), move it into a top-level drag layer first. Convert its current `worldBound` position with the layer's `WorldToLocal`, set `left` and `top` from the result, and only then set `position: absolute`. Switching to absolute without `left` and `top` makes it jump to the layer's top-left corner. +4. Find the slot under the pointer by testing each slot's `worldBound.Contains(evt.position)`. The dragged item and its children sit on top of the slot, so `panel.Pick` returns them instead. +5. On PointerUp, drop into a valid slot or animate back to the start position. Also finish the drop on PointerCaptureOut, because capture can end without a PointerUp (a window switch, for example) and the item would stay stuck mid-drag. +6. Call `evt.StopPropagation()` in the pointer callbacks so the item doesn't also act as a button. + +Show drag state with USS classes rather than inline styles, so the look stays in the stylesheet: + +```csharp +target.AddToClassList("dragging"); +slot.AddToClassList("drop-target"); +``` + +## Inventory and crafting defaults + +When the user asks for an inventory, equipment, or crafting screen, build these unless the request describes a static display: + +- Items drag between slots: inventory, equipment, and hotbar. +- Items snap to grid positions or equipment slots, and equipment slots accept only matching item types (head, chest, weapon). +- Stackable items show a quantity. +- Crafting slots accept ingredients, and recipe slots accept only the item types the recipe uses. + +Checklist: + +- A manipulator class with its four pointer callbacks, attached to each item +- Slots that act as drop targets, each with a rule for what it accepts +- USS classes for the dragging, valid-target, and invalid-target states +- Item data stored separately from the visual elements (a C# list or dictionary, or data binding), so moving an element and moving an item are the same operation +- Visual feedback: a drag shadow, slot highlighting, and hover states diff --git a/skills/using-unity/references/create-ui/references/uitk-skill.md b/skills/using-unity/references/create-ui/references/uitk-skill.md new file mode 100644 index 0000000..d4e8e9d --- /dev/null +++ b/skills/using-unity/references/create-ui/references/uitk-skill.md @@ -0,0 +1,166 @@ +# UI Toolkit guide + +Understand, edit, and generate UI Toolkit UI: UXML layouts, USS styles, the scene component that displays them, and the C# that drives them. + +Paths that start with `references/` resolve to the skill folder; paths that start with `Assets/` resolve to the Unity project. Replace `` in documentation URLs with the project's Editor version, for example `6000.7`. Read `references/uitk-testing.md` in a separate call (together they're longer than one shell command prints), and skip it for a screen with one or two states and no interactions (a compass, a timer, a single gauge), which doesn't use the test framework. + +## Contents + +- Work in few steps +- Docs to read first +- Understanding and editing +- Generation +- Scene setup +- USS +- UXML, events, and custom controls +- Assets and icons +- C# +- Console messages +- Checks + +## Work in few steps + +Every step re-reads the whole conversation, so the number of steps drives the cost of a run. + +- **CLI:** these commands and flags cover a UI build with the `com.unity.pipeline` package 0.10 or later, so don't load the `unity-cli` skill or look up their help unless one fails: + + | Task | Command | + |---|---| + | Keep Play mode running unfocused | `editor set_auto_tick` and `editor.playmode set_run_in_background`, before every `editor.playmode start` | + | Undo that after Play mode | `editor.playmode set_run_in_background --enabled false` and `editor set_auto_tick --enabled false`, after `editor.playmode stop` | + | Compile | `script recompile`, then poll `script recompile_status` | + | Run C# | `script eval --file ` | + | Read the Console | `console status` for the `cursor` and counts, then `console get --since --level error` for messages | + | Play mode | `editor status`, `editor.playmode start`, `editor.playmode stop` | + | Capture | `capture game_view --source screen --width --height --output-path Temp/UIReview/.png` (project-relative; Unity doesn't import `Temp/`) | + | Capture Editor UI | `capture editor_window --window --output-path Temp/UIReview/<name>.png` (not in batch mode) | + | Tests | `test run --async-tests true`, `test status` | + | Packages | `package add --name <name> --confirm true`, `package status` | + + - Run each as `unity command <name> ...`. Parameter names use hyphens (`--async-tests`, `--output-path`, `--interval-ms`); underscores are rejected. Don't send its output to `/dev/null` or cut it by line position: the CLI can print a warning line before the header, so grep the output for the word you want (`completed`, `playing`, `error`). + - Play mode: turn on auto tick and Run In Background before you enter Play mode. Without both, an unfocused Editor stays on frame 1. Run In Background ships in builds, so use the command, which records the project's value: after `editor.playmode stop`, `--enabled false` puts that value back. Turn auto tick off too, because it persists. + - Game view capture: `--width` and `--height` default to 1280×720, and the capture is scaled to that size, so pass the Game view's own size or a non-16:9 view comes out stretched. + - Recompile, which also imports new and changed files. Poll the recompile status: it says `triggered` or `compiling` until it's done, then `completed` (followed by any compile errors), `up_to_date` or `idle`. + - Never run `console clear`: it also deletes the user's own Console entries. Older warnings stay in the Console and look current, so note the `cursor` from `console status` before a step and read only what came after it with `console get --since <cursor>`. + - Eval (`script eval --file Temp/<name>.cs`) runs C# and prints its `return` value. The file has no `using` lines, so write fully qualified type names and call extension methods as static methods (`UnityEngine.UIElements.UQueryExtensions.Q(root, "name")`). Use `FindAnyObjectByType`; `FindFirstObjectByType` is deprecated. + - Entering Play mode can report a network error while the domain reloads; poll the editor status until it shows `"playMode":"playing"`. + - Test status says `running`, then `completed: <passed>/<total> passed`; `--format json` adds each failure's message. + - After `package add`, poll the package status until it says `completed`; `idle` means the add never started, so check the add's output. Leave out `--wait`: the domain reload after the install drops the connection, and the command reports a network error even when the install works. +- **Review loop:** with the mock HUD test, copy the test script from `references/uitk-testing.md` and run it after each edit; it recompiles, reports compile errors, runs the test, and lists the captures in one step. Don't write your own. Without the test framework, and for the in-context capture, do each pass as one command with the capture script in `references/uitk-testing.md`. +- **Decide quickly:** pick names, layout, palette, and sample content without weighing alternatives at length; the review passes catch what needs to change. +- **Time-box detours:** if a detail (an open dropdown menu, a hover state, a capture artifact) still isn't confirmed after two attempts, stop, mention it in the final report, and move on; the review passes matter more than any one detail. +- **Batching:** write all the files of a step in one tool call, then compile once; run the Editor setup script and the first test run in one command; open all the captures of a pass in one message. +- **Docs:** fetch the Panel Renderer page and the USS properties reference, in one parallel batch; fetch other pages below only for a feature you use that this guide doesn't cover. +- **Edit in place:** in phase 2, change token values and add or edit selectors with targeted edits; rewriting a whole stylesheet or controller costs as much as writing it the first time. +- **Editor setup:** do the Panel Settings, theme, scene objects, and scene save in one `script eval` script. Test Unity objects with `if (!component)`, not `??` or `?.`: in the Editor a missing component is a placeholder object, so `GetComponent<T>() ?? AddComponent<T>()` never adds it. +- **Built-in controls:** read the `UssClassName` fields of all the controls you style in one `script eval`. + +## Docs to read first + +USS properties and components vary between Editor versions. Before writing a USS file, open the documentation page for the feature in the target `<VERSION>`. Entries that start with `references/` refer to files in this skill, not documentation pages. + +| Building | Read | +|---|---| +| Runtime UI in a scene | [Panel Renderer component](https://docs.unity.com/en-us/engine/<VERSION>/manual/uitoolkits/uielements/uie-support-for-runtime-ui/uie-render-runtime-ui/panel-renderer-component.md), [Panel Settings properties](https://docs.unity.com/en-us/engine/<VERSION>/manual/uitoolkits/uielements/uie-support-for-runtime-ui/uie-render-runtime-ui/uie-runtime-panel-settings.md), [Theme Style Sheet](https://docs.unity.com/en-us/engine/<VERSION>/manual/uitoolkits/uielements/uie-uss/uie-tss.md) | +| Styles | [USS properties reference](https://docs.unity.com/en-us/engine/<VERSION>/manual/uitoolkits/uielements/uie-uss/properties/reference.md), [Custom properties](https://docs.unity.com/en-us/engine/<VERSION>/manual/uitoolkits/uielements/uie-uss/variables/custom-properties.md) | +| Hover, press, and state animation | [USS transitions](https://docs.unity.com/en-us/engine/<VERSION>/manual/uitoolkits/uielements/uie-uss/properties/uie-transitions.md) | +| Backgrounds, 9-slice, gradients | [Set background images](https://docs.unity.com/en-us/engine/<VERSION>/manual/uitoolkits/uielements/uie-uss/properties/uib-styling-ui-backgrounds.md) | +| Shadows, blur, tint effects | [Built-in filters](https://docs.unity.com/en-us/engine/<VERSION>/manual/uitoolkits/uielements/uie-uss/uss-filter/built-in-filters.md) | +| Built-in controls | [Visual elements reference](https://docs.unity.com/en-us/engine/<VERSION>/manual/uitoolkits/uielements/uie-element-ref.md) | +| Text | [Work with text](https://docs.unity.com/en-us/engine/<VERSION>/manual/uitoolkits/uielements/uie-work-with-text.md) | +| Input and callbacks | [Events](https://docs.unity.com/en-us/engine/<VERSION>/manual/uitoolkits/uielements/uie-events.md), [Manipulators](https://docs.unity.com/en-us/engine/<VERSION>/manual/uitoolkits/uielements/uie-events/uie-manipulators.md) | +| Drag and drop | [Create a drag-and-drop UI](https://docs.unity.com/en-us/engine/<VERSION>/manual/uitoolkits/uielements/uie-events/uie-event-examples/uie-create-drag-and-drop-ui.md), then `references/uitk-pointermanipulator-guide.md` | +| Reusable controls | [Create a custom control](https://docs.unity.com/en-us/engine/<VERSION>/manual/uitoolkits/uielements/uie-structure-ui/uie-custom-controls/uie-create-custom-controls.md), [Customize UXML attributes](https://docs.unity.com/en-us/engine/<VERSION>/manual/uitoolkits/uielements/uie-structure-ui/uie-custom-controls/custom-control-customize-uxml-attributes.md) | +| Values that follow a data object | [Runtime data binding](https://docs.unity.com/en-us/engine/<VERSION>/manual/uitoolkits/uielements/uie-data-binding/uie-runtime-binding.md), [Binding modes](https://docs.unity.com/en-us/engine/<VERSION>/manual/uitoolkits/uielements/uie-data-binding/uie-runtime-binding/mode-update.md) | +| Rings, charts, custom shapes | `references/uitk-painter2d.md` | +| Mock HUD tests and tests for controls and interactions | `references/uitk-testing.md` | +| Icons | `references/uitk-svg-icons.md` | +| Look and feel | `references/ui-visual-design.md` | + +## Understanding and editing + +Explain UI structure as a tree: + +``` +[ElementType] name="elementName" class="class1 class2" +├── [ChildType] name="childName" +│ └── [GrandchildType] +└── [ChildType] class="another-class" +``` + +Edit only the USS selectors and UXML elements covered by the request. If you rename a name, update every C# query that uses it. Preserve existing formatting and references. Rewrite the entire file only when the changes affect most of its content, so users can review the diff. + +## Generation + +A screen, menu, panel, or HUD is `.uxml` + `.uss` + a controller script (`.cs`) for live values and interactions, in a saved scene; a "static layout" is just the UXML and USS. Read requests generously: "proper buttons" have hover, focus, and pressed states, "working UI" responds to input and shows live values, and an inventory or crafting screen is a slot grid with drag and drop (`references/uitk-pointermanipulator-guide.md`). + +Build new UI in two phases, so the UI works before you spend time on its look. + +**Phase 1: function.** Reuse the project's USS, UXML, Panel Settings, and theme files (search `Assets/` only; Panel Settings under `Packages/`, such as a render pipeline's debug window, belong to packages). Write the USS and UXML for the structure with plain styles, and define colors, sizes, and spacing once as USS custom properties so phase 2 restyles in one place. Write every file complete before the Editor imports it, because a half-written UXML is a parse error. Then set up the scene, write the controller (C# section), and test it (Checks 1–4). + +**Phase 2: theme and quality.** Theme with `references/ui-visual-design.md`: direction, palette, type scale, depth, interactive states, motion, and SVG icons (`references/uitk-svg-icons.md`); Painter2D (`references/uitk-painter2d.md`) for rings and charts, USS transitions for state changes. Style the child parts of composite controls too (a Slider's tracker and dragger, a Toggle's checkmark, a ScrollView scroller's tracker and dragger, and hide its Editor-style arrow buttons), because the default theme styles them separately. Review (Check 5), then check the screen over the real scene (Check 6). + +Apply exact values the user gives (hex colors, pixel sizes, spacing) as given, in either phase. + +## Scene setup + +1. Reuse an existing Panel Settings asset, because panels that share one also share focus navigation and sort order. If there is none, create one in the Editor setup script with `ScriptableObject.CreateInstance<PanelSettings>()` and save it with `AssetDatabase.CreateAsset(settings, "Assets/UI/PanelSettings.asset")`. +2. Give it a theme in `themeStyleSheet`: a `.tss` from the project, or a new one containing `@import url("unity-theme://default");`. Built-in controls render unstyled without a theme. +3. Add a Panel Renderer to a GameObject in the scene and set its Panel Settings and UXML through `SerializedObject` (fields `m_PanelSettings` and `sourceAsset`), because the C# properties set from a script don't always reach the saved scene. UI Document isn't the default for new UI, so use it only when editing a scene that already has one. +4. Save an untitled scene with an explicit path, for example `EditorSceneManager.SaveScene(scene, "Assets/Scenes/HUDDemo.unity")`, because saving it without a path opens a modal Save As dialog that blocks the Editor. +5. Save the scene, and confirm both references in the saved `.unity` file. + +Editor UI (EditorWindow, PropertyDrawer) needs no Panel Settings or scene. + +## USS + +USS is a subset of CSS that changes between Editor versions, so don't write a property or selector from CSS memory. Check it for `<VERSION>` first: properties in the [USS properties reference](https://docs.unity.com/en-us/engine/<VERSION>/manual/uitoolkits/uielements/uie-uss/properties/reference.md), selectors on the [USS selectors](https://docs.unity.com/en-us/engine/<VERSION>/manual/uitoolkits/uielements/uie-uss/selectors.md) page, and gradients on the Set background images page. The importer drops what it doesn't know with only a warning, so a missing feature shows up as a style that silently does nothing. When a feature isn't listed, use UXML order or nesting for stacking, child margins for spacing, explicit classes for structural selectors, and Painter2D (`references/uitk-painter2d.md`) for gradients. + +- **CSS features USS doesn't have:** no `border` shorthand (use `border-width` and `border-color`), `outline`, `pointer-events` (use `picking-mode="Ignore"` in UXML), `box-shadow` (use a nested element behind the panel), or structural pseudo-classes such as `:nth-child` and `:first-child` (use explicit classes). +- **Tint:** `-unity-background-image-tint-color` multiplies the image's colors (alpha included), so it can't brighten an image: for a hover highlight, tint the resting state below white. +- **Wrapping:** a Label grows to fit its text, so long text needs a constrained width and `white-space: normal` to wrap. +- **Theme imports:** write a `.uss` before the `.tss` that imports it. A theme imported before its stylesheet exists drops the import silently, and the custom properties stay unresolved until the `.tss` is reimported (`AssetDatabase.ImportAsset` with `ImportAssetOptions.ForceUpdate`). +- **Images in UXML:** an image attribute (a Tab's `icon-image`, an Image's `image`) needs the full asset reference, `project://database/<path>?fileID=<id>&guid=<guid>&type=3#<name>`, with the IDs from `AssetDatabase.TryGetGUIDAndLocalFileIdentifier`; a bare path doesn't load. USS `url(...)` takes a bare path. +- **Where styles live:** in USS classes, so themes and states can override them; inline `style="..."` only for one-off values. Asset URLs are `url("project://database/Assets/...")`; web URLs don't load. +- **Layout:** prefer `flex-grow` and percentages, with fixed pixel sizes for icons, bars, and fixed panels. Skip default values. +- **Field inputs:** a long label squeezes a built-in field's input (`.unity-base-field__input`) to nothing, and the default theme's flex settings override `width`. Size inputs with `flex-basis`, `flex-grow: 0`, and `flex-shrink: 0`. +- **Debugging:** debug style and layout issues by querying elements and reading their `resolvedStyle` properties through `script eval` in Play mode, because it shows the values after every stylesheet and inline style has applied. + +## UXML, events, and custom controls + +- Declare `<ui:UXML xmlns:ui="UnityEngine.UIElements">` (Editor UI adds `xmlns:uie="UnityEditor.UIElements"`), link the stylesheet with `<ui:Style src="Screen.uss" />`, and put the screen under one root `VisualElement` with a class, so one selector can theme, hide, or animate the whole screen. +- A custom control's `xmlns` prefix maps to its exact C# namespace, with matching case and no assembly or class name: `xmlns:custom="Game.UI.Custom"`. +- UXML can't attach handlers. Use `button.clicked += OnPlay;` or `RegisterCallback<ClickEvent>` (and other events) in the controller, and a `PointerManipulator` subclass attached with `element.AddManipulator(...)` for reusable interactions such as drag and drop (`references/uitk-pointermanipulator-guide.md`). +- **Custom controls:** `[UxmlElement]` on a `partial` class, `[UxmlAttribute]` on its properties, for elements that appear on several screens. +- **Data binding:** bind when many values follow one data object, such as a character sheet; for a few HUD values, set properties in the controller. Binding paths are relative to the data source (no type-name prefix), and display-only values need the `ToTarget` mode. + +## Assets and icons + +Reuse existing project icons first, then generate SVG icons, and use an image generator only for icons too detailed for SVG paths. Reference images in USS with `background-image: url("project://database/Assets/UI/Textures/icon.png");`. Import SVGs as `references/uitk-svg-icons.md` describes, because the default import crops each icon to its drawn shape. + +## C# + +- **Getting elements (Panel Renderer):** register the versioned UI reload callback, unregister it on disable or destroy, and query elements inside it, as the Panel Renderer pages show. The tree is rebuilt on every reload, so references taken elsewhere go stale. Store the callback's `version` and return early when it hasn't changed, because the callback also runs on register and on re-enable, and subscribing to button events again makes each click fire twice. +- **Reaching the UI from scripts:** the Panel Renderer has no root property (UI Document has `rootVisualElement`), so keep the callback's root in a public property on the controller (for example `Root`), for Play-mode `script eval` scripts and tests. +- **Getting elements (UI Document):** query `rootVisualElement` in `OnEnable`. +- **Styling:** `AddToClassList()` for anything a stylesheet should override; `element.style.*` for per-frame animation and computed values, because inline styles beat USS selectors. +- **Other:** fonts are TextCore `FontAsset` and `PanelTextSettings` (TextMesh Pro assets belong to uGUI). Build EditorWindows in `CreateGUI()`, in an `Editor` folder or Editor-only assembly. Place scripts next to their UXML and USS unless the project keeps them elsewhere. + +## Console messages + +| Console message | Cause | Fix | +|---|---|---| +| Warning `UAL0010` or `UAL0013` on a UI script | The type has a static field, static auto-property, or static event | Use `const` and instance fields, or mark a type that needs static read-only data `[NoAutoStaticsCleanup]` (namespace `Unity.Scripting.LifecycleManagement`) | + +## Checks + +1. After the files compile, the Console has no UXML import errors or USS warnings about unknown properties or selectors. +2. Enable the UI Test Framework if the project doesn't have it (`references/uitk-testing.md`), except for a screen with one or two states and no interactions. +3. Run the mock HUD test (`references/uitk-testing.md`) and check its captures quickly for missing, clipped, overlapping, or unreadable elements. Write Edit Mode tests only for a reusable control. +4. The saved scene's Panel Renderer (or UI Document) references the Panel Settings and the UXML. +5. Two review passes: in each, make a theme change, rerun the mock HUD test, and review the fresh captures against the checklist in `references/ui-visual-design.md` (phase 1 and in-context captures don't count). A third pass only for a defect a capture shows. +6. Capture the Game view in Play mode once, over the real scene, with the capture script in `references/uitk-testing.md` (one command). If Play mode stays on frame 1 after a second try, skip the capture and say so in the final report instead of debugging Play mode. + +Fallback: without the UI Test Framework, enter Play mode and read through `script eval`, for each named element, whether `root.Q(name)` finds it and its `layout` size, instead of adding logging to the controller. Review Game view captures instead of the mock HUD test. + +If a check fails, reread the doc page for that feature before changing the files again. diff --git a/skills/using-unity/references/create-ui/references/uitk-svg-icons.md b/skills/using-unity/references/create-ui/references/uitk-svg-icons.md new file mode 100644 index 0000000..a5b1fee --- /dev/null +++ b/skills/using-unity/references/create-ui/references/uitk-svg-icons.md @@ -0,0 +1,39 @@ +# SVG icons + +## Contents + +- When to use SVG +- Import and use +- Drawing icons + +## When to use SVG + +Use SVG for simple icons that can be drawn with paths: arrows, chevrons, checkmarks, close, menu, plus and minus, and geometric symbols. Use an image generator for illustrations, photorealistic content, and detailed artwork, because the importer drops the SVG features it doesn't support and those icons lose parts. + +## Import and use + +Replace `<VERSION>` in this URL with the project's Editor version, for example `6000.7`, and read the page before importing: [Work with vector graphics](https://docs.unity.com/en-us/engine/<VERSION>/manual/uitoolkits/uielements/uie-ui-renderer/work-with-vector-graphics.md). It lists the importer settings and the SVG features the importer supports. + +1. Save each icon as its own file in the project, for example `Assets/UI/Icons/chevron-right.svg`. +2. An SVG imports as a UI Toolkit Vector Image by default, but cropped to the shape it draws, so icons drawn on one 24×24 `viewBox` come out at different sizes and a chevron stretches to fill its element. Set the importer's viewport option to Preserve Viewport through `SerializedObject` (`m_ViewportOptions` = `1`), then call `SaveAndReimport()`, because setting the importer's C# property from a script doesn't save. +3. Reference the icon from USS: + + ```uss + .icon-chevron-right { + background-image: url("project://database/Assets/UI/Icons/chevron-right.svg"); + width: 24px; + height: 24px; + } + ``` + +4. Color the icon from USS with `-unity-background-image-tint-color`. Tint multiplies the icon's colors, so author icons in white (`#FFFFFF`). A white icon takes the tint color exactly. + +## Drawing icons + +Draw every icon of a screen on a 24×24 `viewBox` with white strokes, `stroke-width="2"`, `fill="none"`, and round caps and joins, so the icons share one size grid and one style. For example, a chevron: + +```svg +<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> + <path d="M8 4l8 8-8 8" stroke="#FFFFFF" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"/> +</svg> +``` diff --git a/skills/using-unity/references/create-ui/references/uitk-testing.md b/skills/using-unity/references/create-ui/references/uitk-testing.md new file mode 100644 index 0000000..5fc37b6 --- /dev/null +++ b/skills/using-unity/references/create-ui/references/uitk-testing.md @@ -0,0 +1,215 @@ +# Test UI Toolkit UI with the UI Test Framework + +The UI Test Framework package (`com.unity.ui.test-framework`) runs UI Toolkit UI in Test Runner tests and simulates input. The **mock HUD test** (Play Mode) sets a screen to each state through the controller, checks its interactions, asserts its layout, and captures it: the quick visual check in the function phase and the review loop in the theme phase, faster and cheaper than playing the game to each state. Write **Edit Mode tests** only for a reusable custom control. + +Skip the framework for a screen with one or two states and no interactions (a compass, a timer, a single gauge): set each state in Play mode with `script eval` and review Game view captures, because the install, assemblies, and runs cost more than they save. If setup still fails after "Avoid getting stuck", verify by reading element sizes through `script eval` in Play mode and a Game view capture, and say so in the final report. + +Paths that start with `Assets/`, `Library/`, `Packages/`, or `Temp/` resolve to the Unity project; paths that start with `references/` resolve to the skill folder. + +## Contents + +- Enable the package +- Set up the test assemblies +- Mock HUD test +- Avoid getting stuck +- Edit Mode tests +- Run the tests +- Capture in Play mode + +## Enable the package + +If `Packages/manifest.json` doesn't list it, run `unity command package add --name com.unity.ui.test-framework --confirm true` (no version, so Package Manager picks the one that ships with the Editor; no `--wait`, because the domain reload after the install drops the connection), poll `package status` until `completed`, then `script recompile_status`. It ships with the Editor, so adding it downloads nothing. Name the package in the final report so the user can remove it. This file has what a mock HUD test needs; read the package docs only if a step fails, and then read only the `.md` files in `Library/PackageCache/com.unity.ui.test-framework@*/Documentation~/`, nothing else in that package. + +| When this step fails | Read in `Documentation~/` | +|---|---| +| Installing or the test assembly setup | `install-and-set-up.md`, `create-your-first-ui-test.md` | +| Choosing a fixture for Play Mode or runtime UI | `test-fixtures/test-ui-in-runtime.md`, `test-fixtures/introduction-to-test-fixtures.md` | +| Edit Mode tests of a custom control | `test-fixtures/test-ui-without-editor-window-dependencies.md` | +| UI not updating between steps | `test-fixtures/trigger-and-update-ui.md`, `simulate/wait-for-next-ui-frame.md` | +| Clicks, hovers and drags | `simulate/click-on-a-visual-element.md`, `simulate/move-mouse-to-a-visual-element.md`, `simulate/drag-an-element-from-one-place-to-another.md` | +| Keyboard and text input | `simulate/press-keys.md`, `simulate/press-tab-or-return.md`, `simulate/type-into-a-text-field.md` | +| Scrolling | `simulate/scroll-in-a-scrollview.md` | +| Yielding across frames | `test-with-coroutines.md` | +| Fixture state leaking between tests | `test-fixtures/debug-ui-test-fixtures.md`, `test-fixtures/ui-test-component/clean-up-objects-after-tests.md` | + +## Set up the test assemblies + +1. Put the scripts under test (the controller, custom controls) in their own assembly definition, because a test assembly can't reference Assembly-CSharp. That new assembly can't reference Assembly-CSharp either, so move the scripts it depends on into it too, and reference the packages they use (for example `Unity.InputSystem`). +2. Write the Play Mode test assembly's `.asmdef` in a `Tests` folder next to the UI, together with the UI's `.asmdef` and before any test script: references to `UnityEngine.TestRunner`, `UnityEditor.TestRunner`, `Unity.UI.TestFramework.Runtime`, and the UI's assembly; `nunit.framework.dll` as a precompiled reference with `overrideReferences` on; and the `UNITY_INCLUDE_TESTS` define constraint. +3. For a reusable control's Edit Mode tests, add a second assembly set to the Editor platform, with the same settings plus `Unity.UI.TestFramework.Editor`. + +## Mock HUD test + +1. **States:** 3–4 of the default, the extremes (lowest health, maximum values, the longest names), brief feedback (a hit marker), and selected, disabled, or locked states. +2. **Testable controller:** a public method per state, and a `ResetState()` that resets every value, effect, timer, and flag, because effects otherwise carry into the next capture. Demo gameplay and input live in a separate script. +3. **The test**, from the skeleton below, builds the screen with the project's real Panel Settings (so layout and scaling match the game), checks an interaction with simulated input, and per state resets, sets the state, captures to `Temp/UIStates/<state>-<background>.png` (outside `Assets/`), logs one `[UI check]` line of element sizes, and asserts that elements meant to have a size have one (not containers that only position children, such as a crosshair anchor). +4. **Backgrounds:** a HUD over the game gets dark and light, because each exposes text that reads on only one; a screen with its own background (a menu, settings, a skill tree) needs only dark. +5. **Simulated time:** USS transitions and scheduled callbacks advance only with `simulate.FrameUpdate()` (200 ms each by default), not real time, so the skeleton runs five frames per state; after one frame, colors are mid-transition, which isn't a styling bug. +6. **Function phase:** look at the captures only for what's broken, fix it, and move on. +7. **Theme phase:** after each theme change, rerun and review the captures of the states it affects against `references/ui-visual-design.md`: two passes, a third only for a defect. + +For an existing screen that still uses a UI Document, call `SetUIContent(document)` in place of `SetPanelRenderer`. Rename the controller, asset paths, states, element names, and the interaction: + +```csharp +using System.Collections; +using System.IO; +using NUnit.Framework; +using UnityEngine; +using UnityEngine.TestTools; +using UnityEngine.UIElements; +using UnityEngine.UIElements.TestFramework; + +public class HUDStatesTest : RuntimeUITestFixture +{ + Camera m_Camera; + HUDController m_Hud; + + [UnityTest] + public IEnumerator States() + { + m_Camera = new GameObject("Background").AddComponent<Camera>(); + m_Camera.clearFlags = CameraClearFlags.SolidColor; + var go = new GameObject("HUD"); + go.SetActive(false); + var panel = go.AddComponent<PanelRenderer>(); +#if UNITY_EDITOR + panel.panelSettings = UnityEditor.AssetDatabase.LoadAssetAtPath<PanelSettings>("Assets/UI/PanelSettings.asset"); + panel.visualTreeAsset = UnityEditor.AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/UI/HUD/HUD.uxml"); +#endif + m_Hud = go.AddComponent<HUDController>(); + go.SetActive(true); + yield return null; + SetPanelRenderer(panel); + simulate.FrameUpdate(); + + simulate.Click(rootVisualElement.Q<Button>("reload-button")); + simulate.FrameUpdate(); + Assert.That(m_Hud.Ammo, Is.EqualTo(30)); + + yield return Capture("low-health", () => m_Hud.SetHealth(10), "health-bar", "ammo-label"); + Object.Destroy(go); + Object.Destroy(m_Camera.gameObject); + } + + IEnumerator Capture(string state, System.Action setState, params string[] sized) + { + foreach (var (background, color) in new[] { ("dark", new Color(0.06f, 0.06f, 0.06f)), ("light", new Color(0.96f, 0.96f, 0.96f)) }) + { + m_Camera.backgroundColor = color; + m_Hud.ResetState(); + setState(); + for (var frame = 0; frame < 5; frame++) + simulate.FrameUpdate(); // 200 ms each, so USS transitions finish before the capture + yield return new WaitForEndOfFrame(); + var log = $"[UI check] {state}:"; + foreach (var name in sized) + { + var element = rootVisualElement.Q(name); + Assert.That(element, Is.Not.Null, name); + Assert.That(element.layout.width > 0 && element.layout.height > 0, $"{name} has no size"); + log += $" {name} {element.layout.width:0}x{element.layout.height:0}"; + } + Debug.Log(log); + var shot = ScreenCapture.CaptureScreenshotAsTexture(); + // 1024 px wide shows layout and color at about half the tokens to review. + var width = Mathf.Min(1024, shot.width); + var height = shot.height * width / shot.width; + var target = RenderTexture.GetTemporary(width, height, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear); + Graphics.Blit(shot, target); + RenderTexture.active = target; + var small = new Texture2D(width, height, TextureFormat.RGB24, false); + small.ReadPixels(new Rect(0, 0, width, height), 0, 0); + RenderTexture.active = null; + RenderTexture.ReleaseTemporary(target); + Directory.CreateDirectory("Temp/UIStates"); + File.WriteAllBytes($"Temp/UIStates/{state}-{background}.png", small.EncodeToPNG()); + Object.Destroy(shot); + Object.Destroy(small); + } + } +} +``` + +## Avoid getting stuck + +| Symptom | Cause | Fix | +|---|---|---| +| The test assembly "has no scripts associated with it", though its folder has one | The script was imported before the `.asmdef` | Delete the script and write it again | +| The test status says `running` for minutes | Compilation failed, so the run never started | Fix the errors that the recompile status lists after `completed` | +| A "save your changes" dialog blocks the Editor | The open scene has unsaved changes | Save the open scenes before every test run | +| A layout assert fails on an empty bar | A fill is zero wide at an empty value | Assert on the bar's track | +| Brief feedback never shows in a capture | The controller's timer runs on game time | Give the controller a way to hold feedback on screen, and set it in the test | + +## Edit Mode tests + +For a reusable custom control, use `UITestFixture` (an empty, unrendered panel) or `EditorWindowUITestFixture<TWindow>` in the Editor test assembly. Add the control to `rootVisualElement`, call `simulate.FrameUpdate()` before each query and assert, simulate input (`Click`, `DoubleClick`, `MouseMove`, `DragAndDrop(from, to)` with `worldBound.center` positions, `TypingText` after focusing, `KeyPress`, `ScrollWheel`), and assert on values, `ClassListContains(...)`, `enabledSelf`, or `resolvedStyle`. + +## Run the tests + +1. Copy this script to `Temp/run-ui-tests.sh` once, and run `bash Temp/run-ui-tests.sh <TestClassName>` after every edit instead of separate compile, test and console checks. Don't write your own or change how it parses output. It saves the open scenes (a "save your changes" dialog would block the run), recompiles, stops on compile errors, runs only the UI's test class (the project's other Play Mode tests would slow the loop and add failures that aren't the UI's), and prints the result, failure messages, and the `[UI check]` lines, Console errors and capture names from this run only. A run takes 15–30 seconds. + +```bash +#!/bin/bash +# Usage: bash Temp/run-ui-tests.sh <TestClassName> [playmode|editmode] +cd "$(dirname "$0")/.." || exit 1 +u() { unity command "$@" 2>&1; } +printf '%s\n' 'UnityEditor.SceneManagement.EditorSceneManager.SaveOpenScenes();' 'return "scenes saved";' > Temp/save-scenes.cs +u script eval --file Temp/save-scenes.cs | grep -q "scenes saved" || echo "warning: couldn't save the open scenes" +# Read only what this run logs: console clear would also delete the user's own entries. +c=$(u console status | grep -oE '"cursor": *[0-9]+' | grep -oE '[0-9]+$') +log() { if [ -n "$c" ]; then u console get --since "$c" "$@"; else u console get --tail 60 "$@"; fi; } +u script recompile > /dev/null +for i in $(seq 1 60); do s=$(u script recompile_status); echo "$s" | grep -qE 'triggered|compiling' || break; sleep 2; done +if echo "$s" | grep -qE 'error CS|"failed": *true|compilationFailed"?: *true'; then + echo "COMPILE ERRORS:"; echo "$s" | grep -oE '[^"]*error CS[^"]*' | head -10; exit 1 +fi +rm -rf Temp/UIStates +u test run --mode "${2:-playmode}" --filter "$1" --async-tests true > /dev/null +sleep 3 +for i in $(seq 1 20); do + t=$(u test status --format json | tr '\n' ' ') + echo "$t" | grep -qE '"status": *"(completed|no_tests)"' && break; sleep 3 +done +echo "$t" | grep -oE '"status": *"[a-z_]+"|"(total|passed|failed)": *[0-9]+' | tr -d '" ' | paste -sd' ' - +echo "$t" | grep -qE '"status": *"running"' && echo "still running after 60 s: check the Console errors below" +echo "$t" | grep -oE '"message": *"[^"]*' | cut -c1-300 | head -5 +log | grep -oE '\[UI check\][^"]*' | cut -c1-300 +log --level error | grep -oE '"message": *"[^"]*' | cut -c1-300 | head -5 +ls Temp/UIStates 2>/dev/null || echo "no captures in Temp/UIStates" +``` + +2. Edit Mode tests: `bash Temp/run-ui-tests.sh <ClassName> editmode`. +3. To find out why something looks wrong, read the element's `resolvedStyle` through eval in Play mode rather than adding logs and rerunning. +4. Keep the tests in the project, and list them, their results, and the capture folder in the final report. + +## Capture in Play mode + +For the in-context capture, and for review passes without the test framework, copy this script to `Temp/capture-in-play.sh` and run it as one command: `bash Temp/capture-in-play.sh ingame [state ...]`. The first name captures the scene as it starts; for each further name, write `Temp/state-<name>.cs` (a C# file for `script eval` that sets that state through the controller and returns a short string) and the script runs it and captures `<name>`. It turns on auto tick and Run In Background (without it an unfocused Editor stays on frame 1) and checks that Play mode got past frame 1. If it's still on frame 1 it prints `FROZEN` and stops. Then skip the capture, mention it in the final report, and don't debug Play mode. When it stops Play mode, it puts the project's Run In Background value back and turns auto tick off. Captures are 1280×720; if the Game view isn't 16:9, set `GAME_W` and `GAME_H` to its size so they aren't stretched. + +```bash +#!/bin/bash +# Usage: bash Temp/capture-in-play.sh <first-name> [state-name ...] +cd "$(dirname "$0")/.." || exit 1 +u() { unity command "$@" 2>&1; } +CAP() { mkdir -p Temp/UIReview; u capture game_view --source screen --width "${GAME_W:-1280}" --height "${GAME_H:-720}" --output-path "Temp/UIReview/$1.png" | grep -oE 'savedPath"?: *"?[^",}]*'; } +printf '%s\n' 'return "frame=" + UnityEngine.Time.frameCount;' > Temp/frame.cs +frame() { u script eval --file Temp/frame.cs | grep -oE 'frame=[0-9]+' | cut -d= -f2; } +# Stop Play mode, put back the project's Run In Background value, and turn auto tick off: both persist. +finish() { u editor.playmode stop > /dev/null; u editor.playmode set_run_in_background --enabled false > /dev/null; u editor set_auto_tick --enabled false > /dev/null; } +u editor set_auto_tick > /dev/null +# Without Run In Background an unfocused Editor stays on frame 1, even with auto tick. +u editor.playmode set_run_in_background > /dev/null +u editor.playmode start > /dev/null +for i in $(seq 1 30); do u editor status | grep -qE 'playMode"?: *"?playing' && break; sleep 1; done +for i in $(seq 1 8); do sleep 1; f=$(frame); [ "${f:-0}" -gt 1 ] && break; done +if [ "${f:-0}" -le 1 ]; then echo "FROZEN at frame ${f:-?}"; finish; exit 2; fi +sleep 2; echo "playing, frame $(frame)" +CAP "$1" +shift +for name in "$@"; do + u script eval --file "Temp/state-$name.cs" | grep -E '^result:|"result"' | cut -c1-200 + sleep 1; CAP "$name" +done +u console status | grep -oE '"consoleErrors": *[0-9]+' +finish +``` diff --git a/skills/using-unity/references/fix-3d-physics-collisions/fix-3d-physics-collisions.md b/skills/using-unity/references/fix-3d-physics-collisions/fix-3d-physics-collisions.md index e489a29..c65e011 100644 --- a/skills/using-unity/references/fix-3d-physics-collisions/fix-3d-physics-collisions.md +++ b/skills/using-unity/references/fix-3d-physics-collisions/fix-3d-physics-collisions.md @@ -9,11 +9,11 @@ required_editor_version: ">=6000.3" ## Important - Use the unity cli (`unity command --format json`) and the `unity-cli` and `unity-pipeline` skills for each step. -- Don't use `using` directives or unqualified types in the `snippet` for `eval`, because the compiler only reads `using UnityEngine`, and a bare `AssetDatabase` or `Object` causes errors (CS0246 / CS0103 / CS0104). `return` what you want to read; it arrives at `data.result.result`. +- Run C# with `unity command script eval --code '<snippet>'`. Don't use `using` directives or unqualified types in the snippet, because the compiler only reads `using UnityEngine`, and a bare `AssetDatabase` or `Object` causes errors (CS0246 / CS0103 / CS0104). `return` what you want to read; it arrives at `data.result.result`. - Create a restore point you can roll back to if your changes fail. - Do only what's asked. Don't change unrelated assets or files. - Avoid long explanations. -- Never leave verification code in the user's script. Never build logging or detection they didn't ask for, because it clutters their project and console. Read state through `eval` instead, as described in [Final step](#final-step). +- Never leave verification code in the user's script. Never build logging or detection they didn't ask for, because it clutters their project and console. Read state through `script eval` instead, as described in [Final step](#final-step). ## Full topic map @@ -178,9 +178,9 @@ If the user's Console shows one of these errors, apply the fix in its row, becau Run these checks in order. If any check fails, reread the [docs pages](#full-topic-map) to find out what you missed, fix it, and run the checks again. -1. Use `console_status` to check the project has zero console errors. +1. Use `console status` to check the project has zero console errors. 2. If the user didn't ask for proof and you don't suspect a fault, stop here. -3. Otherwise, enter Play mode once and reproduce the case. Read the outcome the user asked for through `eval`, such as whether the bullet's Rigidbody position stopped at the wall, not just the field you changed. Don't add logging or take screenshots, because they cost time and leave changes behind. +3. Otherwise, enter Play mode once and reproduce the case. Read the outcome the user asked for through `script eval`, such as whether the bullet's Rigidbody position stopped at the wall, not just the field you changed. Don't add logging or take screenshots, because they cost time and leave changes behind. 4. Exit Play mode and check again that the console has zero errors. ## Final report diff --git a/skills/using-unity/references/generate-editor-search-query/generate-editor-search-query.md b/skills/using-unity/references/generate-editor-search-query/generate-editor-search-query.md index 97a4147..0584918 100644 --- a/skills/using-unity/references/generate-editor-search-query/generate-editor-search-query.md +++ b/skills/using-unity/references/generate-editor-search-query/generate-editor-search-query.md @@ -1,12 +1,17 @@ --- name: generate-editor-search-query description: Generates Unity Search queries and opens the Search window to find assets or scene objects. Use when the user asks to find, filter, or list assets, GameObjects, components, or references in the Editor, not on disk. -enabled: true -modes: [agent, ask] --- Translate natural-language Unity Editor search requests into useful Unity Search queries, explain them briefly, and open the Unity Search window with the query when appropriate. +## Important + +- Use the unity cli (`unity command --format json`) and the `unity-cli` and `unity-pipeline` skills for each step. +- Create a restore point you can roll back to if your changes fail. +- Do only what's asked. Don't change unrelated assets or files. +- Avoid long explanations. + ## Default Behavior If the prompt explicitly says Unity Search, Quick Search, Search window, open Search, or asks for a Unity Search query, handle the search request with this skill even when the target belongs to another domain such as lighting, UI, physics, audio, or animation. @@ -19,11 +24,11 @@ For requests such as "find", "search", "locate", "list", "filter", "look up", "w 4. Open Unity Search by running the Editor-side snippet unless the user explicitly asks for query text only. 5. If opening Search fails, return the query and tell the user to paste it into Unity Search manually. -Do not open Search when the user says "do not open Search", "query only", "what query should I use", "just give me the query", or similar. +Do not open Search when the user says "do not open Search", "query only", "what query should I use", "just give me the query", or similar, because the user has asked for the text only. -If the user asks for a general explanation, project overview, folder-structure summary, architecture walkthrough, gameplay-system summary, or "how do I" programming answer, do not use this skill unless the prompt explicitly asks for Unity Search, a Search query, or opening the Search window. +If the user asks for a general explanation, project overview, folder-structure summary, architecture walkthrough, gameplay-system summary, or "how do I" programming answer, do not use this skill unless the prompt explicitly asks for Unity Search, a Search query, or opening the Search window, because this skill only builds queries and opens the Search window. -If the user refers to "this", "selected", or "current" without an attached asset, scene object, visible name, or path, ask for the name/path instead of inventing one. +If the user refers to "this", "selected", or "current" without an attached asset, scene object, visible name, or path, ask for the name/path instead of inventing one, because a guessed name produces a query that finds the wrong thing. ## Scope @@ -34,28 +39,58 @@ Scope read-only Unity Search / Quick Search queries to: - path, label, type, filename, keyword, and reference-oriented asset searches - selected or named assets when the name/path is available from the conversation or attachment -Do not install packages, run menu commands, edit assets, modify scenes, search external documentation, search repository text, inspect build logs, delete results, fix search results, or perform dependency graph analysis. If the user asks to act on results, first open Search or provide the query, then ask for confirmation before any separate modifying skill or workflow. +Do not install packages, run menu commands, edit assets, modify scenes, search external documentation, search repository text, inspect build logs, delete results, fix search results, or perform dependency graph analysis, because this skill is read-only and only opens the Search window. If the user asks to act on results, first open Search or provide the query, then ask for confirmation before any separate modifying skill or workflow, because acting on results changes the project. -## References +## Full topic map Before generating non-trivial queries, read [references/query-patterns.md](references/query-patterns.md). Before opening the Search window, read [references/open-search-window.md](references/open-search-window.md). -Official English references: +Before you go forward with a workflow or diagnosis: + +1. Open and read the [documentation page(s)](#full-topic-map) that cover the specific subject related to what you intend to do or fix and check if you've missed anything. +2. Name the file(s) you read in your response. + +This is because your training knowledge about Unity might be out of date, incorrect, or for the wrong Unity version. + +Prefer `WebFetch` over `WebSearch` — faster and lands on the exact reference. Only fetch what you need. Replace `<VERSION>` with the following before fetching: + +- **Package on docs.unity3d.com**: The package version, eg `@6.6` or `@2.0`. Check the package version if unsure. +- **docs.unity.com**: The product version, eg `7000.0` + +For the Unity version, use the major and minor version from `m_EditorVersion` in `ProjectSettings/ProjectVersion.txt`, eg `6000.0` for `6000.0.47f1`, because the docs site has no pages under a full release number. + +If the Editor install folder has a `Data/Documentation` folder (eg `...Unity/Hub/Editor/6000.6.0b2/Editor/Data/Documentation`), read the html files from the `en/Manual` folder (`<editor-install>/Editor/Data/Documentation/en/Manual/<page>.html`). + +Otherwise the docs pages are online at `https://docs.unity.com/en-us/engine/<VERSION>/manual/unity-editor/editor-navigating-managing/editor-searching/`. + +- **Unity Search** — local `search-overview.html`, online `search-overview.md`. Providers, filters, and opening the Search window. + - Search expressions — local `search-expressions.html`, online `search-overview/search-textual-query/search-expressions.md`. Nested queries such as `ref={t:texture}`. -- [Unity Search](https://docs.unity3d.com/Manual/search-overview.html) -- [Search expressions](https://docs.unity3d.com/Manual/search-expressions.html) -- [SearchService.ShowWindow](https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Search.SearchService.ShowWindow.html) +### API reference + +The API is `UnityEditor.Search.SearchService` (mainly `SearchService.ShowWindow`), part of the Unity Engine. It is versioned by Unity version, so check the project's Unity version before relying on a specific class or method. + +1. Use the `unity-cli` skill to check the project's Unity version. +2. If the Editor install folder has a `Data/Documentation` folder, grep the html files in `<editor-install>/Editor/Data/Documentation/en/ScriptReference` (eg `Search.SearchService.ShowWindow.html`), and skip the remaining steps. +3. Otherwise, fetch and cache `https://docs.unity3d.com/<VERSION>/Documentation/ScriptReference/xrefmap.yml`. This file lists every public API member's fully qualified name as a `uid` (eg `uid: 'UnityEditor.Search.SearchService.ShowWindow(UnityEditor.Search.SearchViewState)'`). +4. Grep the yml file locally for a class or method instead of refetching per lookup. The file is large (about 6 MB), so don't read the whole file. +5. Convert the `uid` to a markdown page: remove the parameters in brackets, lowercase it, replace `.` with `/`, and add `.md`. Then fetch `https://docs.unity.com/en-us/engine/<VERSION>/script-reference/<converted uid>`, eg `https://docs.unity.com/en-us/engine/<VERSION>/script-reference/unityeditor/search/searchservice/showwindow.md`. All overloads are on the same page. + - Links inside the pages start with `/engine/`. Add `https://docs.unity.com/en-us` before them. + - If the page doesn't exist for that Unity version, use the `href` in the `xrefmap.yml` entry instead (eg `href: 'Search.SearchService.ShowWindow.html'` => `https://docs.unity3d.com/<VERSION>/Documentation/ScriptReference/Search.SearchService.ShowWindow.html`). + +Always use the docs for the project's Unity version rather than relying on training knowledge, since APIs are frequently marked obsolete between versions. ## Passing C# to `script eval` -`script eval` compiles a **statement block, not a file**. Two consequences, both compile errors: +`script eval` compiles a **statement block, not a file**, so write the code without `using` directives and with fully qualified types. If the code doesn't compile, look up the error here: -- **No `using` directives.** The compiler reads `using UnityEditor;` as a resource-disposal - statement and rejects it (`CS0210`). -- **Types must be fully qualified.** A bare `SearchService` does not resolve (`CS0246`), and a - bare `Object` is ambiguous with `object` (`CS0104`). +| Error | Cause | Fix | +| --- | --- | --- | +| `CS0210` | A `using` directive, such as `using UnityEditor;`, which the compiler reads as a resource-disposal statement | Remove the directive and qualify the types | +| `CS0246` | An unqualified type, such as `SearchService` | Use the full name, such as `UnityEditor.Search.SearchService` | +| `CS0104` | A bare `Object`, which is ambiguous with `object` | Use `UnityEngine.Object` | The `unity-cli` skill owns the prerequisites — installing the CLI, confirming a connected Editor, adding the project's `com.unity.pipeline` package, and discovering the command catalog. You need @@ -74,7 +109,7 @@ Use the simplest query that is likely to produce the requested result. - For selected/current wording, use the known selected asset name or path only if it is present in the chat context; otherwise ask for it. - For broad relationship requests such as "where is Rigidbody used", use a simple keyword or component query first, then mention that a scripted audit is separate if the user needs exhaustive code/property analysis. - For requests that mix Search with repair work, generate and open the query first; do not modify results unless the user explicitly confirms a separate follow-up action. -- Do not invent unsupported filters for uncertain requests. If a request cannot be expressed reliably with Unity Search syntax, open the closest safe query and state the limitation. +- Do not invent unsupported filters for uncertain requests, because an unsupported filter returns no results or the wrong results. If a request cannot be expressed reliably with Unity Search syntax, open the closest safe query and state the limitation. ## Opening Unity Search @@ -86,7 +121,7 @@ When opening Search: 2. Prefer asset and scene providers for this v1 skill. 3. Fall back to active providers if a provider is unavailable. 4. Log the query that was opened. -5. Never claim Search opened if the command failed. +5. Never claim Search opened if the command failed, because the user would look for a window that isn't there. ## Response Format @@ -106,7 +141,15 @@ Paste this into Unity Search. If the request is ambiguous but still searchable, choose the most likely query and mention the assumption. Ask a question only when the search target cannot be inferred, such as "find the thing" with no asset, scene, type, name, or context. -## Validation Checklist +## Final step + +If you ran the snippet, check it worked before you report, because `script eval` can fail without the window opening: + +1. Read the `script eval` result. It succeeded only if it returns `Opened Unity Search with query: <query>` with the query you generated. If it returns a compile error, look the error up in the table under "Passing C# to `script eval`", fix the snippet, and run it again once. +2. Run `unity command console status` to check the console has zero errors, because a runtime exception in the snippet shows up there rather than in the result. If there are errors, run `unity command console get -- --tail 20 --level error` to read them. Confirm the command names with `unity command` first, because they differ between `com.unity.pipeline` versions. +3. If either check still fails, reread the [docs pages](#full-topic-map) for the project's Unity version to find what you missed. If you can't fix it, follow the fallback behavior in [references/open-search-window.md](references/open-search-window.md): don't claim Search opened, and give the user the query to paste in. + +Take no screenshots, because they take more time and the result string already says whether the window opened. Before reporting success: @@ -115,3 +158,13 @@ Before reporting success: - Search was opened only when the user did not opt out - any fallback or uncertainty is stated plainly - no asset, scene, package, project setting, or search result was modified + +## Final report + +End with a short report to the user, in the [response format](#response-format), so they know what ran and what is left for them: + +1. The query you generated. +2. Whether Unity Search opened with it, or why it didn't (the user opted out, `script eval` is unavailable, or the command failed). +3. Any side effects or fallbacks: the temporary file you used to base64-encode the query and that you deleted it, or that Search fell back to active providers. +4. Any assumption you made about an ambiguous request, and any limitation of the query. +5. What the user needs to do next, such as paste the query into Unity Search manually, or confirm a separate follow-up if they asked to act on the results. diff --git a/skills/using-unity/references/implement-in-app-purchases/SECURITY.md b/skills/using-unity/references/implement-in-app-purchases/SECURITY.md new file mode 100644 index 0000000..10e6a64 --- /dev/null +++ b/skills/using-unity/references/implement-in-app-purchases/SECURITY.md @@ -0,0 +1,15 @@ +# Security notes: implement-in-app-purchases + +This skill can have the agent run C# in the user's live Unity Editor with `unity command script eval`, to read project and Play mode state while it sets up or checks in-app purchases. Automated skill scanners flag running code in the Editor as a powerful capability. It is intentional, and it is limited by the safeguards below. + +## Accepted risks + +| Risk | Capability | Why it is accepted | +|---|---|---| +| `SEC_POWER_CAP` | Runs C# in the user's live Editor through `unity command script eval` | It only reaches the Editor the user already has open, on their own machine, as that user, so it grants nothing they couldn't do themselves. It also changes the project: it installs the Unity IAP package (`com.unity.purchasing`) when it is missing. | + +## Mitigations + +- **Only the user's own Editor.** The code runs in the Editor open on this machine. It can't reach another machine or another user's Editor. +- **Nothing left behind.** The skill tells the agent never to leave verification code in the user's scripts, and to create a restore point before changes. +- **No remote code.** Nothing downloaded from outside is executed. diff --git a/skills/using-unity/references/implement-in-app-purchases/implement-in-app-purchases.md b/skills/using-unity/references/implement-in-app-purchases/implement-in-app-purchases.md index 939f592..92e0d92 100644 --- a/skills/using-unity/references/implement-in-app-purchases/implement-in-app-purchases.md +++ b/skills/using-unity/references/implement-in-app-purchases/implement-in-app-purchases.md @@ -138,9 +138,9 @@ Read the [EntitlementStatus API](https://docs.unity3d.com/Packages/com.unity.pur Do the following checks: -1. Check the project has zero console errors. Use `console_status` for counts. +1. Check the project has zero console errors. Use `console status` for counts. 2. Stop there unless the user asked you to prove it works or you suspect a specific fault. -3. If you do enter Play mode, do it once only to chase a fault you already suspect. Read the world through `eval` rather than adding logging. Take no screenshots, because they take too much time. +3. If you do enter Play mode, do it once only to chase a fault you already suspect. Read the world through `script eval` rather than adding logging. Take no screenshots, because they take too much time. If a check fails, go back and reread the [docs pages](#full-topic-map) to find out what you missed. @@ -160,6 +160,6 @@ After writing code that uses this package, also read the code back and check it, Report the following to the user, in this order: 1. What changed: each file you changed, with the old and new API calls or values where they apply (for example, `IStoreListener.ProcessPurchase` → `OnPurchasePending`). -2. How you verified it: the outcome of each Final step check, including the console error count and anything you read through `eval` in Play mode. +2. How you verified it: the outcome of each Final step check, including the console error count and anything you read through `script eval` in Play mode. 3. Incidental side effects: anything you touched beyond the requested change, such as packages you installed or upgraded, project or Services settings you changed, generated files (for example tangle classes or `IAPProductCatalog.json`), and temporary files you created or removed. 4. Follow-up the user must do, for example product setup in App Store Connect or the Google Play Console, and sandbox testing on a device. Include the manual steps that the path reference file lists. diff --git a/skills/using-unity/references/import-and-optimize-cad-models/SECURITY.md b/skills/using-unity/references/import-and-optimize-cad-models/SECURITY.md new file mode 100644 index 0000000..258f4fd --- /dev/null +++ b/skills/using-unity/references/import-and-optimize-cad-models/SECURITY.md @@ -0,0 +1,15 @@ +# Security notes: import-and-optimize-cad-models + +This skill has the agent write C# and run it inside the user's live Unity Editor, to create and edit Asset Transformer Toolkit RuleSets, Importers and LOD settings. It doesn't say which command runs the code; with the `unity` CLI that is `unity command script eval`. Automated skill scanners flag running generated code as a powerful capability. It is intentional, and it is limited by the safeguards below. + +## Accepted risks + +| Risk | Capability | Why it is accepted | +|---|---|---| +| `SEC_POWER_CAP` | Runs agent-written C# in the user's live Editor | It only reaches the Editor the user already has open, on their own machine, as that user, so it grants nothing they couldn't do themselves. The code only edits RuleSet, Importer and LOD assets and components in the user's own project. No code fetched from a remote source is run. | + +## Mitigations + +- **Only the user's own Editor.** The code runs in the Editor open on this machine. It can't reach another machine or another user's Editor. +- **Narrow purpose.** The scripts create or modify RuleSets, Importers and LOD settings through the documented Asset Transformer Toolkit API, then read each change back to check it. +- **No remote code.** The agent runs C# it writes from this skill's own recipes. Nothing downloaded from outside is executed. diff --git a/skills/using-unity/references/import-and-optimize-cad-models/import-and-optimize-cad-models.md b/skills/using-unity/references/import-and-optimize-cad-models/import-and-optimize-cad-models.md new file mode 100644 index 0000000..4c32aaa --- /dev/null +++ b/skills/using-unity/references/import-and-optimize-cad-models/import-and-optimize-cad-models.md @@ -0,0 +1,101 @@ +--- +name: import-and-optimize-cad-models +description: >- + Imports and optimizes CAD models and point clouds with Asset Transformer Toolkit (Pixyz). Make + sure to use this skill when the user wants to import CAD or point cloud files, or build RuleSets, + Actions, or LODs for them. +required_packages: + com.unity.industry.toolkit: ">=4.0.0" +--- +## Important + +- Use the unity cli (`unity command --format json`) and the `unity-cli` and `unity-pipeline` skills for each step. +- Before making changes, establish a baseline of the current behavior so you can tell whether a later result is actually caused by your change. +- Create a restore point you can roll back to if your changes fail. +- Do only what's asked. Don't change unrelated assets or files. +- Never leave verification code in the user's scripts. Never build logging or detection they didn't ask for, because it clutters their project and console. +- Avoid long explanations. + +## Full topic map + +Before you go forward with a workflow or diagnosis: + +1. Open and read the [documentation page(s)](#full-topic-map) that cover the specific subject related to what you intend to do or fix and check if you've missed anything. +2. Name the file(s) you read in your response. + +This is because your training knowledge about Unity might be out of date, incorrect, or for the wrong Unity version. + +The docs pages are local markdown copies of the Asset Transformer Toolkit package documentation, stored at `<project-folder>/Library/PackageCache/com.unity.industry.toolkit@*/`. Read only the .md files in that specific `PackageCache` subfolder. You must not look at non-.md files, or look outside at other Library or PackageCache folders, otherwise it takes too much time. + +- `Documentation~/import-models.md`: importing models with an Importer. +- `Documentation~/use-the-rule-engine.md`: RuleSets, Rules, and Actions. +- `Documentation~/lod-generator.md`: generating LODs. +- `Documentation~/prepare-optimize-model.md`: preparing and optimizing imported models. + +If a page you need isn't in that folder, because some package versions don't ship all their docs, read the same page online under `https://docs.unity3d.com/Packages/com.unity.industry.toolkit@<VERSION>/manual/`. Use the `.html` file names, for example `manual/use-the-rule-engine.html`, because this package's online docs have no `.md` variant and a `.md` URL returns 404. Prefer `WebFetch` over `WebSearch` — faster and lands on the exact reference. Only fetch what you need. Replace `<VERSION>` with the following before fetching: + +- **Package on docs.unity3d.com**: The package version, eg `@6.6` or `@2.0`. Check the package version if unsure. +- **docs.unity.com**: The product version, eg `7000.0` + +For this skill, use the `com.unity.industry.toolkit` version from `Packages/packages-lock.json`, eg `4.0`. + +### Before you start: check the package version +This skill needs Asset Transformer Toolkit 4.0.0 or later (`com.unity.industry.toolkit`). Earlier versions don't have the `ATTAssistantUtilities` API every workflow below relies on. + +1. Read the resolved version of `com.unity.industry.toolkit` from `Packages/packages-lock.json` (fall back to `Packages/manifest.json`). +2. **Not installed:** tell the user this workflow needs Asset Transformer Toolkit 4.0 or later, which is an entitled Unity package they may need access to through their Unity plan, and stop. Don't add it to the manifest yourself, because the install fails without that entitlement. +3. **Installed below 4.0.0:** tell the user which version you found and that 4.0 or later is required, and ask before upgrading. Don't fall back to older APIs, raw C# against internal types, or reflection, because this skill's workflows only work through the 4.0 `ATTAssistantUtilities` API. +4. **4.0.0 or later:** continue. + +### API reference +The API is in the `Unity.Pixyz.Plugin4Unity` and `UnityEditor.PixyzPlugin4Unity` namespaces, part of the `com.unity.industry.toolkit` package. It is versioned by package version, not Unity version (e.g. `@4.0`), so check the project's installed package version before relying on a specific class or method. + +The package's online docs have no scripting API reference for the RuleSet, Rule, RuleBlock, or `ATTAssistantUtilities` APIs, so the reference files below are the only documentation of the members this skill uses. Use them instead of searching online or relying on training knowledge, because APIs often change between major package versions. + +1. Use the `unity-cli` skill to check the installed package version. +2. Fetch `https://docs.unity3d.com/Packages/com.unity.industry.toolkit@<VERSION>/xrefmap.yml` (replace `<VERSION>` with the installed package version, e.g. `4.0`) and grep it for the class you need. If it has an entry, read the page its `href` points to, because that page matches the installed version. +3. If it has no entry, use the reference file below that covers the class. +4. If neither covers the member you need, tell the user rather than guessing a member name or using reflection, because a wrong name fails to compile and reflection is not available. + +### Technical Notes +- Pixyz Plugin is the former name of Asset Transformer Toolkit. Call it Asset Transformer Toolkit when you address the user, unless the user calls it Pixyz. +- Most classes and code are in the `Unity.Pixyz.Plugin4Unity.Editor` assembly. +- Asset Transformer Toolkit is NOT the same product as Asset Transformer Studio (formerly Pixyz Studio). NEVER rely on information about Asset Transformer Studio, because its features and APIs differ. + +### Importers +- Asset Transformer Toolkit imports 3D files from outside the project. +- When you modify an Importer, NEVER start a reimport unless the user asked for one, because an import can take a very long time. +- Modify Importer fields through `SerializedObject` and `SerializedProperty`. NEVER use reflection to access or modify Importer fields, because reflection is not available. +- To create an Importer for a file, or to reimport a model with an existing ImporterScriptableObject, read [references/create-importer](references/create-importer.md). + +### RuleSets and Actions +Read [references/rulesets-and-actions](references/rulesets-and-actions.md) +Read [references/ruleset-api](references/ruleset-api.md) when the RuleSet API is needed. +Read [references/rule-api](references/rule-api.md) when the Rule API is needed. +Read [references/ruleblock-api](references/ruleblock-api.md) when the RuleBlock API is needed, including `ActionBase.Id` for constructing `RuleBlock` instances. + +### Levels of Detail +Read [references/lods](references/lods.md) + +## Final step + +This skill changes Importer, RuleSet, and LOD settings in the Editor, not runtime scripts, so a clean console and a read-back of each change are enough. Run these checks in order: + +1. Run `unity command console status --format json` and check `groundTruth.consoleErrors` is zero and `compilationFailed` is false. +2. Read back each asset you changed with `script eval`, because a change can run without errors and still not stick: + - **Importer:** reload the asset with `AssetDatabase.LoadAssetAtPath`, then check each property you set through `SerializedObject.FindProperty` holds the new value. + - **RuleSet:** reload the asset, check `RulesCount`, the Action IDs in each Rule (`GetRule(i).GetBlock(j)`), and that `IsValid()` returns `true`. Check it against the [validation checklist](references/rulesets-and-actions.md#validation-checklist). Then read back every Action parameter you changed and compare it with the requested value. Skip parameters you set to a scene GameObject, because Unity doesn't serialize references to scene objects and they read back as null. Report those as temporary instead (see [Path C](references/rulesets-and-actions.md#path-c-success)). + - **LOD settings:** reload the Importer or GameObject, check the LOD rule count and types match what you set, and read back every LOD parameter you changed and compare it with the requested value. +3. Stop here unless the user asked for more proof or you suspect a specific fault. In that case, inspect the asset or scene through `script eval`. Don't enter Play mode, because Asset Transformer Toolkit runs only in Edit mode and can't run Importers or RuleSets in Play mode. If an import or RuleSet run is still in progress, don't verify its results yet. Report it under **Background tasks** instead. + +If any check fails, go back and reread the [docs pages](#full-topic-map) to find out what you missed, fix it, and run the checks again. + +## Final report + +Return these sections in order: + +1. **Changes**: each Importer, RuleSet, or LOD setting you created or changed, with old and new values. +2. **Side effects**: anything you changed that the user didn't name, such as the save folder `EnsureImporterSaveFolder` created, or "None". +3. **Verification**: the results of the final step checks. +4. **Background tasks**: any import or RuleSet run still in progress, and that the user must wait for it to finish. +5. **Follow-up**: anything the user must do, such as refreshing the Inspector to see changes or setting a parameter by hand. diff --git a/skills/using-unity/references/asset-transformer-toolkit/references/create-importer.md b/skills/using-unity/references/import-and-optimize-cad-models/references/create-importer.md similarity index 69% rename from skills/using-unity/references/asset-transformer-toolkit/references/create-importer.md rename to skills/using-unity/references/import-and-optimize-cad-models/references/create-importer.md index f0342d7..0dc3a5f 100644 --- a/skills/using-unity/references/asset-transformer-toolkit/references/create-importer.md +++ b/skills/using-unity/references/import-and-optimize-cad-models/references/create-importer.md @@ -4,28 +4,28 @@ --- -If a new Importer does not need to be created, skip to Step 3 +## Workflow ### Step 1: Pre-Flight -- Check whether an importer asset already exists for this file. If it does, skip to Step 3. -- Verify the file to be imported exists. -- Verify the file type is supported by Pixyz/Asset Transformer Toolkit using `ATTAssistantUtilities.CanImportFile()`. -- Check what kind of file (eg. point cloud, CAD) is it. Find the Importer type that would best match it. +1. Check whether an Importer asset already exists for this file. If it does, skip to Step 3, because creating a second Importer for the same file duplicates the imported model. +2. Check the file to import exists. +3. Call `ATTAssistantUtilities.CanImportFile()` to check Asset Transformer Toolkit supports the file type. If it returns `false`, tell the user the format isn't supported and stop. +4. Identify the kind of file, such as point cloud or CAD, and pick the best-matching type from `ATTAssistantUtilities.GetImporterTypes()`. ### Step 2: Create Importer -- Create the appropriate Importer asset with the path to the file to be imported. The path must be relative to the Application.dataPath. -- If there are issues, fix and revalidate. Do not exceed 3 iterations. -Do not continue if this step cannot be completed successfully. +1. Call `ATTAssistantUtilities.CreateImporter()` with the absolute system path to the file, the type from Step 1, and the folder from `ATTAssistantUtilities.EnsureImporterSaveFolder()`. +2. If it fails, fix the problem and try again. Stop after three attempts, because repeated failures usually mean the approach is wrong, and more attempts waste the user's time. +3. If you can't create the Importer, tell the user why and stop, because every later step needs it. ### Step 3: Configure Importer -- If requested, change the importer's settings. -- If requested, assign the requested RuleSet to the Importer. -- If requested, make changes to the LOD generation. -Continue only if asked to also import the file. The import process can be very long, so NEVER assume you must import the file unless it was requested. +1. If the user asked to change Importer settings, change them through `SerializedObject`, using the paths from `ATTAssistantUtilities.GetImporterProperties()`. +2. If the user asked for a RuleSet on the Importer, assign it. +3. If the user asked for LOD changes, follow the Levels of Detail workflow. +4. Stop here unless the user asked you to import the file, because an import can take a very long time. ### Step 4: Import -- Start the asynchronous import using `ATTAssistantUtilities.ImportFile()`. -- Report whether the import process started successfully. Remind the user this is a background process. +1. Start the asynchronous import with `ATTAssistantUtilities.ImportFile()`. +2. Report whether the import started, and remind the user it runs in the background. ## Importer utility functions @@ -115,7 +115,7 @@ public static void ImportFile(string importerPath) ### Technical Notes - Because import is an asynchronous process, the imported files may not yet exist in the project by the time the prompt finishes execution. -- The imported model will always be saved to the same directory that the ImporterScriptableObject lives in. -- Importers are designed to be extended. Check which Importer types exist in the project using `ATTAssistantUtilities.GetImporterTypes()` instead of making assumptions like a point cloud file always maps to the PointCloudImporterScriptableObject. -- Only one import should be processing at a time. +- The toolkit always saves the imported model in the same folder as its ImporterScriptableObject. +- Users can add their own Importer types. Check which Importer types exist in the project with `ATTAssistantUtilities.GetImporterTypes()` instead of assuming, for example, that a point cloud file always maps to `PointCloudImporterScriptableObject`. +- Run only one import at a time, because imports run in the background and you can't tell which result belongs to which import while several are running. - When creating a new ImporterScriptableObject, save it under the folder returned by `ATTAssistantUtilities.EnsureImporterSaveFolder()`. This reflects the user-configured save folder from Project Settings and defaults to `"Assets/3DModels"`. diff --git a/skills/using-unity/references/import-and-optimize-cad-models/references/lods.md b/skills/using-unity/references/import-and-optimize-cad-models/references/lods.md new file mode 100644 index 0000000..9c0fb8d --- /dev/null +++ b/skills/using-unity/references/import-and-optimize-cad-models/references/lods.md @@ -0,0 +1,70 @@ +## Contents +- [Paths](#paths) — CADImporterScriptableObject, Scene Object, PointCloudImporter, Other Importer +- [LOD utility functions](#lod-utility-functions) — `GetLODRules`, `LODRuleDescription`, `LODParameterInfo` +- [Technical Notes](#technical-notes) + +--- + +## Paths + +Choose the path that matches the object you're working with. + +### Path A: CADImporterScriptableObject +Choose this path if working with an object that is or inherits from CADImporterScriptableObject. +1. Call `GetLODRules` to list the LOD rule types in the project, and pick the ones that fit the request. +2. Find the LODGenerator property in the Importer. +3. Make the requested change. +4. Check the Generator has no more than 7 rules, because each rule adds one LOD after LOD0 and Unity supports at most 8 LODs including LOD0. + +### Path B: Scene Object +Choose this path when the user asks you to work with a scene GameObject directly. +1. If no `UnityEngine.PixyzPlugin4Unity.Components.LODGeneratorComponent` exists anywhere in the GameObject's hierarchy, add one to the GameObject. +2. Call `GetLODRules` to list the LOD rule types in the project. +3. Make the requested change. + +### Path C: PointCloudImporter +Choose this path when working with a PointCloudImporterScriptableObject object. +1. Check the request only enables or disables LOD generation or sets the number of LODs, because the PointCloudImporter supports nothing else, such as choosing a LODRule type. If it asks for anything else, tell the user the PointCloudImporter doesn't support it and stop. +2. Make the requested change on the Importer, not on a LODGeneratorComponent, because point cloud models don't get one. + +### Path D: Other Importer +Choose this path if working with a different importer type. +This is a user-defined Importer, not part of Asset Transformer Toolkit, so this skill has no exact steps for it. +1. Try the requested change, up to three attempts, because without instructions for this Importer, repeated failures mean you're guessing. +2. If it still fails, tell the user you can't change LODs on this Importer type and they need to change them by hand. + +## LOD utility functions + +The following functions are from `Unity.Pixyz.Plugin4Unity.Editor.AI.ATTAssistantUtilities`. + +### `GetLODRules` + +Returns all available `LODRule` implementations and their parameters. Use this before constructing or modifying a LOD configuration to discover valid types. + +```csharp +public static LODRuleDescription[] GetLODRules() +``` + +Returns a `LODRuleDescription[]`, each containing the type name, assembly-qualified name, and parameter list. + +### `LODRuleDescription` + +| Field | Type | Description | +|-------|------|-------------| +| `Name` | string | Unqualified class name of the LODRule type. | +| `QualifiedName` | string | Assembly-qualified name, suitable for `Type.GetType`. | +| `Parameters` | `LODParameterInfo[]` | Configurable properties on this LODRule type. | + +### `LODParameterInfo` + +| Field | Type | Description | +|-------|------|-------------| +| `Name` | string | Property name. | +| `Type` | string | Property type name. | + +### Technical Notes +- The user needs to refresh the Inspector to see your changes. +- In an Importer's settings for LOD generation, the number of LODs set to generate does not include LOD0. There will always be one more LOD than the setting says. For example, setting the PointCloudImporter's NumberofLODs setting to 1 will result in the model having two LODs: LOD0 and LOD1. +- While Unity supports up to 8 LODs including LOD0, the PointCloudImporter is a special case that only supports 7. +- With the exception of models imported by the PointCloudImporter, models that were imported with LODs will have a LODGeneratorComponent script. +- LODs are separate from RuleSets and Actions. Don't use RuleSets or Actions for any LOD task, because they can't change LOD settings. diff --git a/skills/using-unity/references/asset-transformer-toolkit/references/rule-api.md b/skills/using-unity/references/import-and-optimize-cad-models/references/rule-api.md similarity index 96% rename from skills/using-unity/references/asset-transformer-toolkit/references/rule-api.md rename to skills/using-unity/references/import-and-optimize-cad-models/references/rule-api.md index 8c0fa7d..088de02 100644 --- a/skills/using-unity/references/asset-transformer-toolkit/references/rule-api.md +++ b/skills/using-unity/references/import-and-optimize-cad-models/references/rule-api.md @@ -5,6 +5,8 @@ --- +The Asset Transformer Toolkit package docs have no scripting API reference for the Rule class, so this file lists the members this skill uses. + ## Rule constructors The Rule API reference contains the following constructors. diff --git a/skills/using-unity/references/asset-transformer-toolkit/references/ruleblock-api.md b/skills/using-unity/references/import-and-optimize-cad-models/references/ruleblock-api.md similarity index 85% rename from skills/using-unity/references/asset-transformer-toolkit/references/ruleblock-api.md rename to skills/using-unity/references/import-and-optimize-cad-models/references/ruleblock-api.md index 97cf80a..5d029aa 100644 --- a/skills/using-unity/references/asset-transformer-toolkit/references/ruleblock-api.md +++ b/skills/using-unity/references/import-and-optimize-cad-models/references/ruleblock-api.md @@ -1,3 +1,5 @@ +The Asset Transformer Toolkit package docs have no scripting API reference for the RuleBlock class or `ActionBase.Id`, so this file lists the members this skill uses. + ## ActionBase properties ### `Id` diff --git a/skills/using-unity/references/asset-transformer-toolkit/references/ruleset-api.md b/skills/using-unity/references/import-and-optimize-cad-models/references/ruleset-api.md similarity index 96% rename from skills/using-unity/references/asset-transformer-toolkit/references/ruleset-api.md rename to skills/using-unity/references/import-and-optimize-cad-models/references/ruleset-api.md index fbc40ee..212ed3b 100644 --- a/skills/using-unity/references/asset-transformer-toolkit/references/ruleset-api.md +++ b/skills/using-unity/references/import-and-optimize-cad-models/references/ruleset-api.md @@ -5,6 +5,8 @@ --- +The Asset Transformer Toolkit package docs have no scripting API reference for the RuleSet class or `RunRuleSet`, so this file lists the members this skill uses. + ## RuleSet methods The RuleSet API reference contains the following methods. diff --git a/skills/using-unity/references/asset-transformer-toolkit/references/rulesets-and-actions.md b/skills/using-unity/references/import-and-optimize-cad-models/references/rulesets-and-actions.md similarity index 61% rename from skills/using-unity/references/asset-transformer-toolkit/references/rulesets-and-actions.md rename to skills/using-unity/references/import-and-optimize-cad-models/references/rulesets-and-actions.md index 834f21a..5adce3b 100644 --- a/skills/using-unity/references/asset-transformer-toolkit/references/rulesets-and-actions.md +++ b/skills/using-unity/references/import-and-optimize-cad-models/references/rulesets-and-actions.md @@ -14,24 +14,24 @@ ## Actions -Actions are classes derived from UnityEditor.PixyzPlugin4Unity.Actions.ActionBase that execute a task on a list of input objects. -It is expected that users will create additional Action classes to extend the Actions available in the base package. +Actions are classes derived from `UnityEditor.PixyzPlugin4Unity.Actions.ActionBase` that run a task on a list of input objects. +Users can write their own Action classes, so call `GetActionsList` to see which Actions the project has instead of assuming. ## RuleSets ### Description -RuleSets are a SerializedObject containing a list of Rule instances, which contain a list of Action instances. RuleSets are used to ensure a set of Actions are executed in a specific order. -RuleSets are derived from ScriptableObject and must end with the '.asset' extension. -RuleSets support conversion to json. This will include information about the Actions they contain. +A RuleSet is a ScriptableObject asset that holds a list of Rules. Each Rule holds a list of RuleBlocks, and each RuleBlock runs one Action. The Editor UI calls RuleBlocks "Actions". A RuleSet runs its Actions in a fixed order. +Save RuleSets with the `.asset` extension, because Unity only saves a ScriptableObject as an asset with that extension. +A RuleSet can convert to JSON, including information about the Actions it contains. ### Modifying RuleSets #### Step 1: Load RuleSet -- Use AssetDatabase.LoadAssetAtPath to load the asset from memory. +1. Load the asset from disk with `AssetDatabase.LoadAssetAtPath`. #### Step 2: Construct the script -- Read the API reference for the RuleSet class. Also read the API reference for the Rule and RuleBlock classes if required. -- Construct a script using the APIs from those files, to run as C# in a live Editor. Here is an +1. Read the API reference for the RuleSet class, and for the Rule and RuleBlock classes if you need them. +2. Write a script with those APIs to run as C# in a live Editor. Here is an example that adds a Decimate Action to a RuleSet: ```csharp @@ -63,48 +63,47 @@ AssetDatabase.SaveAssets(); return $"Added Decimate action to {path} (Rule index 0)"; ``` -A proper script for modifying a RuleSet has the following traits: -- Does not use the ScriptableObject API (this bypasses necessary event triggers). +Change the RuleSet only through the RuleSet, Rule, and RuleBlock methods, as in the example. Don't edit its fields through `SerializedObject`, because that skips the events the RuleSet raises to update its UI and internal state. #### Step 3: Validation -- Run the script as C# in a live Editor. -- Validate the RuleSet against the validation checklist. +1. Run the script as C# in a live Editor. +2. Check the RuleSet against the [validation checklist](#validation-checklist). ### Creating RuleSets #### Step 1: Create RuleSet -- Create the UnityEditor.PixyzPlugin4Unity.RuleEngine.RuleSet asset. -Continue to Step 2 if actions need to be added to the RuleSet. If not, add the GetContextGameObjects action and jump to Step 3. +1. Create the `UnityEditor.PixyzPlugin4Unity.RuleEngine.RuleSet` asset. +2. If the user wants Actions in the RuleSet, continue to Step 2. Otherwise, add a Rule with only the GetContextGameObjects Action and jump to Step 3, because every Rule must start with GetContextGameObjects or RunRules to be valid. #### Step 2: Add Actions **Preflight** -- Ensure the RuleSet exists. -- Choose the combination of Actions that will best perform the requested procedure. NEVER create new Actions without explicit permission. Instead, use the Actions returned by `GetActionsList`. -- Divide Actions into Rules based on the GameObject they need to act upon. Each Rule initially executes on every GameObject unless the input is narrowed with a Filter action. Example: If only lights need to be disabled and only meshes with >10000 vertices need to be decimated, two rules will be needed as this is two different groups of GameObjects. +1. Check the RuleSet exists. +2. Choose the combination of Actions that will best perform the requested procedure. NEVER create new Actions without explicit permission, because a new Action adds C# code to the user's project that they didn't ask for. Instead, use the Actions returned by `GetActionsList`. +3. Divide Actions into Rules based on the GameObject they need to act upon. Each Rule initially executes on every GameObject unless the input is narrowed with a Filter action. Example: If only lights need to be disabled and only meshes with >10000 vertices need to be decimated, two rules will be needed as this is two different groups of GameObjects. **Adding Rules** -- Check whether the existing Rule(s) in the RuleSet is just the GetContextGameObjects action. If it is, append the group of actions to it rather than creating a new Rule. -- If a new Rule needs to be created, add it to the RuleSet. -- Add Actions to the Rules. -- Set action parameters if required — see Setting Action Parameters below. +1. Check whether an existing Rule holds only the GetContextGameObjects Action. If it does, append the Actions to it instead of creating a new Rule, because an empty starter Rule does nothing on its own. +2. Otherwise, add a new Rule to the RuleSet. +3. Add the Actions to the Rules. +4. If the user asked for specific Action settings, set them as described in [Setting Action Parameters](#setting-action-parameters). **Technical Notes** - All Actions derive from the ActionBase class. - Actions are located in the UnityEditor.PixyzPlugin4Unity.Actions namespace. #### Step 3: Validation -- Validate the RuleSet logic using the validation checklist. +1. Check the RuleSet against the [validation checklist](#validation-checklist). ### Setting Action Parameters #### Step 1: Gather data -- Gather any missing information needed to call `ATTAssistantUtilities.SetActionParameter`. If you need to retrieve a GlobalObjectId, first read the GlobalObjectId class to choose the correct function to call. -- Call `ATTAssistantUtilities.SetActionParameter` to set the parameter. -- If the result is false and not an exception, retry a maximum of three times. -- Follow a path based on the result. +1. Gather any missing information needed to call `ATTAssistantUtilities.SetActionParameter`. If you need a GlobalObjectId, first read the `GlobalObjectId` API page to choose the correct function to call. +2. Call `ATTAssistantUtilities.SetActionParameter` to set the parameter. +3. If it returns `false` without an exception, check the parameter name against `GetActionDefinitions` and retry, up to three times in total, because `false` means the name didn't match a field and a corrected name usually fixes it. +4. Follow the path that matches the result. #### Path A: AITypeSecurityException Follow these steps if `ATTAssistantUtilities.SetActionParameter` threw an AITypeSecurityException. @@ -128,17 +127,17 @@ Perform this step if `ATTAssistantUtilities.SetActionParameter` always returns f All paths are exclusive. **Technical Notes** -- For the Decimate action specifically, if mesh quality is going to be set to a preset, the Criterion parameter must also be set to Quality. -- Prefer using presets when possible rather than individually setting each value. -- If a preset is used, avoid changing values the preset changed unless requested otherwise. +- For the Decimate Action, if you set mesh quality to a preset, also set the Criterion parameter to Quality, because the preset only takes effect when Criterion is Quality. +- Use a preset rather than setting each value, because presets set related values that work together. +- If you use a preset, don't change values the preset set unless the user asks, because that breaks the combination the preset chose. **Safety & Constraints** -1. **One-Strike Rule**: If `ATTAssistantUtilities.SetActionParameter` throws an AITypeSecurityException, you MUST TERMINATE the task immediately. Do NOT use raw C# execution, reflection, or any other method to bypass this. Follow the steps in Path A as your final actions. +1. **One-Strike Rule**: If `ATTAssistantUtilities.SetActionParameter` throws an AITypeSecurityException, you MUST TERMINATE the task immediately, because the toolkit deliberately blocks setting this parameter from code, and any workaround would defeat that safeguard. Do NOT use raw C# execution, reflection, or any other method to bypass this. Follow the steps in Path A as your final actions. ### Running RuleSets -Use `ATTAssistantUtilities.RunRuleSet()` instead of the RuleSet's public API to run a RuleSet. -Only one RuleSet must be running at a time. +Use `ATTAssistantUtilities.RunRuleSet()` instead of the RuleSet's public API to run a RuleSet, because it reports progress through Unity's background task progress window, so the user can watch the run. Running it through the RuleSet API shows no progress. +Run only one RuleSet at a time, because a running RuleSet changes scene objects, and a second one would act on objects the first is still changing. When running a RuleSet, remind the user it is a background task/asynchronous. diff --git a/skills/using-unity/references/initialize-ai-navigation/SECURITY.md b/skills/using-unity/references/initialize-ai-navigation/SECURITY.md new file mode 100644 index 0000000..fead3ae --- /dev/null +++ b/skills/using-unity/references/initialize-ai-navigation/SECURITY.md @@ -0,0 +1,15 @@ +# Security notes: initialize-ai-navigation + +This skill can have the agent run C# in the user's live Unity Editor with `unity command script eval`, to read project and Play mode state while it sets up or checks AI navigation. Automated skill scanners flag running code in the Editor as a powerful capability. It is intentional, and it is limited by the safeguards below. + +## Accepted risks + +| Risk | Capability | Why it is accepted | +|---|---|---| +| `SEC_POWER_CAP` | Runs C# in the user's live Editor through `unity command script eval` | It only reaches the Editor the user already has open, on their own machine, as that user, so it grants nothing they couldn't do themselves. It also changes the project: it installs the AI Navigation package (`com.unity.ai.navigation`) when it is missing. | + +## Mitigations + +- **Only the user's own Editor.** The code runs in the Editor open on this machine. It can't reach another machine or another user's Editor. +- **Nothing left behind.** The skill tells the agent never to leave verification code in the user's scripts, and to create a restore point before changes. +- **No remote code.** Nothing downloaded from outside is executed. diff --git a/skills/using-unity/references/initialize-ai-navigation/initialize-ai-navigation.md b/skills/using-unity/references/initialize-ai-navigation/initialize-ai-navigation.md index 572000a..26e63a2 100644 --- a/skills/using-unity/references/initialize-ai-navigation/initialize-ai-navigation.md +++ b/skills/using-unity/references/initialize-ai-navigation/initialize-ai-navigation.md @@ -68,7 +68,7 @@ The agent and query API is `UnityEngine.AI` (`NavMeshAgent`, `NavMesh`, `NavMesh Always use the docs for the installed package and Unity version rather than relying on training knowledge, since APIs are frequently marked obsolete between versions (e.g. the `OffMeshLink` component is deprecated in favour of `NavMeshLink`). -### Passing C# to `eval` +### Passing C# to `script eval` `script eval` compiles a **statement block, not a file**, so these are compile errors rather than warnings: @@ -139,7 +139,7 @@ Follow this general order. See the Component Setup Guide in the reference for de 6. **Scripts** — movement, patrol, click-to-move, animation coupling (see Common Recipes in reference) ### 4. Validation -After setup, read these values with `eval` (fully qualified) rather than checking the Scene view by eye, because a NavMesh that looks right can still be missing or mismatched: +After setup, read these values with `script eval` (fully qualified) rather than checking the Scene view by eye, because a NavMesh that looks right can still be missing or mismatched: 1. Each `NavMeshSurface` has baked data: `navMeshData` isn't null. 2. Each `NavMeshSurface.agentTypeID` matches the `NavMeshAgent.agentTypeID` of the agents that walk on it. @@ -156,9 +156,9 @@ If a check fails, fix it and run the checks again before the Final step. Do the following checks: -1. Check the project has zero console errors. Use `console_status` for counts. +1. Check the project has zero console errors. Use `console status` for counts. 2. Stop there unless the user asked you to prove it works or you suspect a specific fault. -3. If you do enter Play mode, do it once only to chase a fault you already suspect. Read the world through `eval` rather than adding logging, for example each agent's `pathStatus` and `remainingDistance` to see whether it reaches its destination. Take no screenshots as they take too much time. +3. If you do enter Play mode, do it once only to chase a fault you already suspect. Read the world through `script eval` rather than adding logging, for example each agent's `pathStatus` and `remainingDistance` to see whether it reaches its destination. Take no screenshots as they take too much time. If a check fails, go back and reread the [docs pages](#full-topic-map) to find out what you missed. diff --git a/skills/using-unity/references/localize-unity-project/SECURITY.md b/skills/using-unity/references/localize-unity-project/SECURITY.md new file mode 100644 index 0000000..3689f67 --- /dev/null +++ b/skills/using-unity/references/localize-unity-project/SECURITY.md @@ -0,0 +1,15 @@ +# Security notes: localize-unity-project + +This skill can have the agent run C# in the user's live Unity Editor with `unity command script eval`, to read project and Play mode state while it localizes or checks the localization of the project. Automated skill scanners flag running code in the Editor as a powerful capability. It is intentional, and it is limited by the safeguards below. + +## Accepted risks + +| Risk | Capability | Why it is accepted | +|---|---|---| +| `SEC_POWER_CAP` | Runs C# in the user's live Editor through `unity command script eval` | It only reaches the Editor the user already has open, on their own machine, as that user, so it grants nothing they couldn't do themselves. It also changes the project: it installs the Localization package (`com.unity.localization`) when it is missing, and switches the active locale while it checks translations. | + +## Mitigations + +- **Only the user's own Editor.** The code runs in the Editor open on this machine. It can't reach another machine or another user's Editor. +- **Nothing left behind.** The skill tells the agent never to leave verification code in the user's scripts, and to create a restore point before changes. +- **No remote code.** Nothing downloaded from outside is executed. diff --git a/skills/using-unity/references/localize-unity-project/localize-unity-project.md b/skills/using-unity/references/localize-unity-project/localize-unity-project.md index 3039d7b..67bdcd5 100644 --- a/skills/using-unity/references/localize-unity-project/localize-unity-project.md +++ b/skills/using-unity/references/localize-unity-project/localize-unity-project.md @@ -227,10 +227,10 @@ If an error appears in the console or the game UI, look it up in [references/tro Run these checks in order. If any check fails, reread the [docs pages](#full-topic-map) to find out what you missed, fix it, and run the checks again. -1. Run `unity command console status` (the `console_status` check) and confirm `groundTruth.consoleErrors` is 0 and `compilationFailed` is false. +1. Run `unity command console status` (the `console status` check) and confirm `groundTruth.consoleErrors` is 0 and `compilationFailed` is false. 2. Run the [table completeness check](references/table-completeness-check.md) and keep its output for the report. 3. Stop there unless the user asked for proof or a specific fault is suspected, such as a label that doesn't change when the locale changes. -4. If a fault is suspected and the change affects runtime behaviour, enter Play mode once to chase it. Read the world through `eval`, for example `LocalizationSettings.SelectedLocale` and the `text` of the label in question, rather than adding logging. Take no screenshots, because they take too much time. Exit Play mode when you're done. +4. If a fault is suspected and the change affects runtime behaviour, enter Play mode once to chase it. Read the world through `script eval`, for example `LocalizationSettings.SelectedLocale` and the `text` of the label in question, rather than adding logging. Take no screenshots, because they take too much time. Exit Play mode when you're done. ## Final report diff --git a/skills/using-unity/references/localize-unity-project/references/translation-strategy.md b/skills/using-unity/references/localize-unity-project/references/translation-strategy.md index 561d832..cc163a6 100644 --- a/skills/using-unity/references/localize-unity-project/references/translation-strategy.md +++ b/skills/using-unity/references/localize-unity-project/references/translation-strategy.md @@ -36,6 +36,6 @@ To efficiently translate an existing project, follow this multi-step workflow: - **Grammar & Tone:** Ensure the tone matches the game's style. For example, use imperative verbs for buttons (e.g., German: "Lauf!" instead of "Laufen") and correct pluralization for labels (e.g., "Punkte" instead of "Punkt"). 3. **Quality Assurance (QA):** - - **Switch locale:** Through `eval`, run `LocalizationSettings.SelectedLocale = LocalizationSettings.AvailableLocales.GetLocale("de");` for each target locale in turn, because a script call is repeatable and doesn't depend on an Editor window being open. + - **Switch locale:** Through `script eval`, run `LocalizationSettings.SelectedLocale = LocalizationSettings.AvailableLocales.GetLocale("de");` for each target locale in turn, because a script call is repeatable and doesn't depend on an Editor window being open. - **Visual Inspection:** Methodically inspect every prefab and scene in the base language and all target languages. - **Layout Fit:** Check for text overflows or "tofu" (missing glyphs). Adjust font sizes or use `ContentSizeFitter` if strings are too long. diff --git a/skills/using-unity/references/manage-sprite-atlas/SECURITY.md b/skills/using-unity/references/manage-sprite-atlas/SECURITY.md new file mode 100644 index 0000000..ebf3d89 --- /dev/null +++ b/skills/using-unity/references/manage-sprite-atlas/SECURITY.md @@ -0,0 +1,16 @@ +# Security notes: manage-sprite-atlas + +This skill has the agent run short C# snippets inside the user's live Unity Editor, to read back `EditorSettings.spritePackerMode` and to check that each atlas it created actually packs. It doesn't say which command runs the code; with the `unity` CLI that is `unity command script eval`. Automated skill scanners flag running generated code as a powerful capability. It is intentional, and it is limited by the safeguards below. + +## Accepted risks + +| Risk | Capability | Why it is accepted | +|---|---|---| +| `SEC_POWER_CAP` | Runs agent-written C# in the user's live Editor | It only reaches the Editor the user already has open, on their own machine, as that user, so it grants nothing they couldn't do themselves. The snippets only read atlas and Editor settings, and pack atlases into the Editor's packing cache. No code fetched from a remote source is run. | + +## Mitigations + +- **Only the user's own Editor.** The code runs in the Editor open on this machine. It can't reach another machine or another user's Editor. +- **Narrow purpose.** The snippets read `EditorSettings.spritePackerMode`, load the atlases the agent created, pack them with `SpriteAtlasUtility.PackAtlases`, and return `spriteCount` and `CanBindTo`. They don't change project assets. +- **No verification code left behind.** The skill tells the agent never to leave verification code in the user's scripts, so checks run only through `script eval`. +- **No remote code.** The agent runs C# it writes from this skill's own instructions. Nothing downloaded from outside is executed. diff --git a/skills/using-unity/references/manage-sprite-atlas/manage-sprite-atlas.md b/skills/using-unity/references/manage-sprite-atlas/manage-sprite-atlas.md index 79f352c..59be7ca 100644 --- a/skills/using-unity/references/manage-sprite-atlas/manage-sprite-atlas.md +++ b/skills/using-unity/references/manage-sprite-atlas/manage-sprite-atlas.md @@ -1,6 +1,7 @@ --- name: manage-sprite-atlas description: Manages SpriteAtlas assets through a prebuild pipeline, covering master and variant atlases, packing settings, and platform overrides. Use when asked to create or optimize sprite atlases. +required_editor_version: ">=6000.3" --- # Unity SpriteAtlas V2 @@ -9,33 +10,123 @@ Provides *editor-safe* procedural knowledge for scripting atlases in Unity proje > ⚠ **Critical V2 Principle**: `SpriteAtlas` is **runtime-only**. `SpriteAtlasAsset` is **editor-only**. Never mix contexts. Always use V2. -## 🚨 CRITICAL: Required Checks and User Inputs Before Implementation +## Important -**ALWAYS perform these checks and ask these questions BEFORE generating any code:** +- Use the unity cli (`unity command --format json`) and the `unity-cli` and `unity-pipeline` skills for each step. +- Run C# with `unity command script eval --caller plugin --skill manage-sprite-atlas --code '<snippet>'`. Don't use `using` directives or unqualified types in the snippet. The compiler reads using `UnityEngine` and a bare AssetDatabase, SpriteAtlas, or Object causes errors (CS0246 / CS0103 / CS0104). `return` what you want to read; it arrives at `data.result.result`. +- Before making changes, establish a baseline of the current behavior so you can tell whether a later result is actually caused by your change. +- Create a restore point you can roll back to if your changes fail. +- Do only what's asked. Don't change unrelated assets or files. +- Never leave verification code in the user's script. Never build logging or detection they didn't ask for. See [Final step](#final-step). +- Avoid long explanations. -### Read the shipped resources before writing code (REQUIRED) +## Full topic map -This skill ships working C# under `resources/`, and the atlas code that goes wrong is almost always +Before you go forward with a workflow or diagnosis: + +1. Open and read the [documentation page(s)](#full-topic-map) that cover the specific subject related to what you intend to do or fix and check if you've missed anything. +2. Name the file(s) you read in your response. + +This is because your training knowledge about Unity might be out of date, incorrect, or for the wrong Unity version. + +For Engine pages: if the Editor install folder has a `Data/Documentation` folder (eg `...Unity/Hub/Editor/6000.6.0b2/Editor/Data/Documentation`), read the html files from the `en/Manual` folder (`<editor-install>/Editor/Data/Documentation/en/Manual/<local file>`), and Script Reference pages from `en/ScriptReference`. + +Otherwise the docs pages are online at `https://docs.unity.com/en-us/engine/<VERSION>/manual/unity2d/sprite/atlas.md`. +Prefer fetching the page directly (for example `WebFetch`) over searching (for example `WebSearch`) — faster and lands on the exact reference. Only fetch what you need, and only search if you don't have the exact URL. Replace `<VERSION>` with the following before fetching: + +- **docs.unity3d.com**: The Unity version, eg `6000.6` +- **Package on docs.unity3d.com**: The package version, eg `@6.6` or `@2.0`. Check the package version if unsure. +- **Engine on docs.unity.com**: The Unity version, eg `6000.3` +- **docs.unity.com**: The product version, eg `7000.0` + +Read the Unity version from `ProjectSettings/ProjectVersion.txt`, and the `com.unity.addressables` major.minor for the Addressables docs from `Packages/packages-lock.json`. + +For Addressables pages: the docs pages are local markdown conversions of the Unity Manual, stored at `<project-folder>/Library/PackageCache/com.unity.addressables@*/`. Read only the .md files in that specific `PackageCache` subfolder. You must not look at non-.md files, or look outside at other Library or PackageCache folders, otherwise it takes too much time. If that folder has no .md files, use the online pages at `https://docs.unity3d.com/Packages/com.unity.addressables@<VERSION>/manual/`, because some packages don't ship their docs. + +The page list, with each page's local file and online URL, is in [references/docs-map.md](references/docs-map.md). + +- [references/api.md](references/api.md): the Script Reference page for each V2 type, plus API pitfalls. + +### API reference + +The API is `UnityEditor.U2D` (`SpriteAtlasAsset`, `SpriteAtlasImporter`, `SpriteAtlasUtility`) and `UnityEngine.U2D` (`SpriteAtlas`, `SpriteAtlasManager`), part of the Unity Engine. It is versioned by Unity version, so check the project's Unity version before relying on a specific class or method. + +1. Use the `unity-cli` skill to check the project's Unity version. +2. If the Editor install folder has a `Data/Documentation` folder (e.g. `.../Unity/Hub/Editor/6000.6.0b2/Editor/Data/Documentation`), grep the html files in the `en/ScriptReference` folder inside, and skip the remaining steps. +3. Otherwise, fetch and cache `https://docs.unity3d.com/<VERSION>/Documentation/ScriptReference/xrefmap.yml` (replace `<VERSION>` with the Unity version, e.g. `6000.3`). This file lists every public API member's fully qualified name as a `uid` (e.g. `uid: 'UnityEngine.Rigidbody.AddForce(UnityEngine.Vector3)'`). +4. Grep the yml file locally for a class or method instead of refetching per lookup. The file is large (about 6 MB), so don't read the whole file. +5. Convert the `uid` to a markdown page: remove the parameters in brackets, lowercase it, replace `.` with `/`, and add `.md`. Then fetch `https://docs.unity.com/en-us/engine/<VERSION>/script-reference/<converted uid>`. For example, `UnityEngine.Rigidbody.AddForce(UnityEngine.Vector3)` => `https://docs.unity.com/en-us/engine/6000.3/script-reference/unityengine/rigidbody/addforce.md`. All overloads are on the same page. + - Constructors use `ctor` (e.g. `unityengine/vector3/ctor.md`), and indexers use `item` (e.g. `unityengine/vector3/item.md`). + - For operators, fetch the class page (e.g. `unityengine/vector3.md`) and follow its link. + - Links inside the pages start with `/engine/`. Add `https://docs.unity.com/en-us` before them. + - If the page doesn't exist for that Unity version, use the `href` in the `xrefmap.yml` entry instead (e.g. `href: 'Rigidbody.AddForce.html'` => `https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Rigidbody.AddForce.html`). + +The Addressables API (`UnityEditor.AddressableAssets`, `UnityEngine.AddressableAssets`) is part of the `com.unity.addressables` package and versioned by package version (e.g. `@2.7`), not Unity version. Use the `unity-cli` skill to check the installed package version, then fetch and cache `https://docs.unity3d.com/Packages/com.unity.addressables@<version>/xrefmap.yml`, which maps each member's fully qualified name to its docs page `href` (e.g. `href: api/UnityEditor.AddressableAssets.Settings.AddressableAssetSettings.html` => `https://docs.unity3d.com/Packages/com.unity.addressables@2.7/api/UnityEditor.AddressableAssets.Settings.AddressableAssetSettings.html`). Grep the yml file locally instead of refetching per lookup, and don't read the whole file. + +Always use the docs for the project's Unity and package versions rather than relying on training knowledge, since APIs are frequently marked obsolete between versions. + +## 🚨 CRITICAL: Default Approach is Prebuild Generation + +**ALWAYS use `IPreprocessBuildWithReport` to automatically generate or update SpriteAtlases during the build pipeline.** This is the DEFAULT and REQUIRED approach unless the user EXPLICITLY requests manual authoring. + +### ❌ DO NOT Create Manual Menu Item Scripts + +**NEVER create scripts with `[MenuItem]` attributes for atlas generation unless explicitly requested.** The prebuild approach eliminates the need for manual clicks. **Only use manual authoring for**: Hand-optimized layouts, specific sprite arrangements, or editor preview requirements. See [Advanced: Manual Authoring](#advanced-manual-authoring-not-default---use-only-when-explicitly-requested). + +## 🚨 CRITICAL: Sprite Source Location Restriction + +**ONLY add sprites from the project's Assets folder. NEVER add sprites from Unity built-in assets, packages, or external locations.** Unity built-in assets cannot be packed into SpriteAtlas, and package assets may cause import/dependency issues. + +## Critical V2 Architecture + +| Context | Component | Purpose | Allowed Usage | +|---------|-----------|---------|---------------| +| **Editor Authoring** | `SpriteAtlasAsset` | Add/remove sprites/folders; store metadata | ✅ Editor scripts only | +| **Editor Settings** | `SpriteAtlasImporter` | Configure texture, packing, platform settings | ✅ Editor scripts only | +| **Editor Packing** | `SpriteAtlasUtility.PackAtlases()` | *Optional* editor preview packing (not for build) | ⚠ Only for preview; atlases auto-pack at build | +| **Runtime** | `SpriteAtlas` | Query packed sprites (read-only) | ✅ Runtime scripts only | +| **Runtime Loading** | `SpriteAtlasManager` | Dynamic loading callbacks | ✅ Runtime scripts only | + +### Forbidden Cross-Context Usage (Common Error Sources) + +| ❌ Invalid Pattern | ✅ Correct Pattern | +|--------------------|-------------------| +| `new SpriteAtlas()` in editor code | Use `SpriteAtlasAsset` + `SpriteAtlasImporter` | +| `AssetDatabase.LoadAssetAtPath<SpriteAtlas>(...)` in editor | Use `SpriteAtlasAsset.Load(...)` | +| `SpriteAtlasAsset.GetPackables()` in editor | Use `SpriteAtlas.GetPackables()` | +| Modifying `SpriteAtlas` in editor scripts | Modify `SpriteAtlasAsset` → reimport → use `SpriteAtlasImporter` | +| Create variants from original packable objects (sprites/folders) | Creating variants from a Master runtime `SpriteAtlas` | + +**NEVER script against `SpriteAtlas` in editor code** — it is *only* for runtime use in V2 except for GetPackables. + +## Procedure + +Run these steps in order. **ALWAYS perform steps 1 to 4 BEFORE generating any code.** + +### 1. Read the shipped resources before writing code (REQUIRED) + +This skill ships working C# under `scripts/`, and the atlas code that goes wrong is almost always code written without reading it first. Open the files for the path you are taking, then write. | Taking this path | Read first | |---|---| -| Any atlas work at all | [resources/authoringvsruntime.cs](resources/authoringvsruntime.cs), [references/common-errors.md](references/common-errors.md) | -| Prebuild generation (the default) | [resources/spriteatlasprebuildgenerator.cs](resources/spriteatlasprebuildgenerator.cs), [resources/enablespritepacking.cs](resources/enablespritepacking.cs), [resources/savespriteatlasasset.cs](resources/savespriteatlasasset.cs) | -| Option B, Addressables late-binding | [resources/buildaddressablespostprocess.cs](resources/buildaddressablespostprocess.cs), [resources/spriteatlaslatebinding.cs](resources/spriteatlaslatebinding.cs), [resources/handlelatebinding.cs](resources/handlelatebinding.cs) | -| Anything that might use an older API | [resources/deprecatedmethods.cs](resources/deprecatedmethods.cs), [resources/dontscriptspriteatlasineditor.cs](resources/dontscriptspriteatlasineditor.cs), [resources/dontpackinruntimebuilds.cs](resources/dontpackinruntimebuilds.cs) | +| Any atlas work at all | [scripts/authoringvsruntime.cs](scripts/authoringvsruntime.cs), [references/common-errors.md](references/common-errors.md) | +| Prebuild generation (the default) | [scripts/spriteatlasprebuildgenerator.cs](scripts/spriteatlasprebuildgenerator.cs), [scripts/enablespritepacking.cs](scripts/enablespritepacking.cs), [scripts/savespriteatlasasset.cs](scripts/savespriteatlasasset.cs) | +| Option B, Addressables late-binding | [scripts/buildaddressablespostprocess.cs](scripts/buildaddressablespostprocess.cs), [scripts/spriteatlaslatebinding.cs](scripts/spriteatlaslatebinding.cs), [scripts/handlelatebinding.cs](scripts/handlelatebinding.cs) | +| Anything that might use an older API | [scripts/deprecatedmethods.cs](scripts/deprecatedmethods.cs), [scripts/dontscriptspriteatlasineditor.cs](scripts/dontscriptspriteatlasineditor.cs), [scripts/dontpackinruntimebuilds.cs](scripts/dontpackinruntimebuilds.cs) | -`resources/` holds 38 files in all, covering custom packers, variants, platform settings, and -runtime access. Browse the directory when your task is not in the table above rather than inventing -an approach. Reaching for the API from memory instead of reading these is the single most common -cause of an atlas that imports cleanly and then does nothing at runtime. +`scripts/` also covers custom packers, variants, platform settings, and runtime access. Browse it +when your task isn't in the table, because writing the API from memory is the most common cause of +an atlas that imports cleanly and then does nothing at runtime. -### 0. Check for Existing Scripts (REQUIRED FIRST STEP) +### 2. Check for Existing Scripts (REQUIRED) **BEFORE generating any code, scan the project for existing SpriteAtlas scripts generated by this skill.** Search for files containing the identifier: `// [UNITY-SKILL:SPRITEATLAS]` +If you find none, go to step 3, because there is nothing to update or overwrite. + **If existing scripts are found, ALWAYS ask the user with this format:** > "I found existing SpriteAtlas scripts in your project: @@ -53,39 +144,24 @@ Search for files containing the identifier: `// [UNITY-SKILL:SPRITEATLAS]` **Then present options:** -- **Option A: Update existing scripts** (Recommended if requirements changed) - - Regenerates scripts at existing paths - - Preserves file locations - - Updates to latest version - - ⚠ May overwrite custom modifications - -- **Option B: Create new scripts with different names** - - Generates alongside existing scripts - - Allows multiple atlas configurations - - Original scripts remain unchanged - - You'll need to specify new names/paths - -- **Option C: Abort (keep existing unchanged)** - - No code generation - - No changes to project - - Use this if you want to keep current setup +- **Option A: Update existing scripts** (Recommended if requirements changed). Regenerates them at the same paths. ⚠ May overwrite custom modifications. +- **Option B: Create new scripts with different names**. Generates alongside the existing scripts, which stay unchanged. You'll need to specify new names or paths. +- **Option C: Abort (keep existing unchanged)**. Makes no changes to the project. **User Choice Handling:** -- **If A chosen**: Regenerate at existing paths, increment version to 2.0.1+ +- **If A chosen**: Regenerate at existing paths, and keep `// [UNITY-SKILL:SPRITEATLAS]` on the first line so the next run finds the scripts again - **If B chosen**: Ask for new script names (e.g., "SpriteAtlasPrebuild_Custom.cs"), then generate - **If C chosen**: Stop immediately, inform user no changes were made -### 1. Delivery Mechanism (REQUIRED) +### 3. Delivery Mechanism (REQUIRED) Ask: "How do you want to deliver the sprite atlases?" **Option A: Built-in Data (Immediate Loading)** - Atlases are included in the build and loaded immediately - Set `includeInBuild = true` -- **Suitable for**: Core UI, main gameplay sprites, always-needed assets -- **Pros**: Simple, no additional packages, instant access -- **Cons**: Increases initial build size, cannot update without new build +- Increases initial build size, and can't update without a new build **Option B: Late-Binding via Addressables (On-Demand Loading)** - Atlases are NOT included in build, loaded on-demand via Addressables @@ -94,9 +170,7 @@ Ask: "How do you want to deliver the sprite atlases?" - Add addressable setup as prebuild step - **🚨 REQUIRED**: Build Addressables content as build step - **🚨 REQUIRED**: Create late-binding runtime loader script -- **Suitable for**: DLC content, optional features, large assets, downloadable content -- **Pros**: Smaller initial build, can update independently, on-demand loading -- **Cons**: Requires Addressables package, async loading, network dependency +- Requires the Addressables package, and loads asynchronously | Use Case | Recommended | |----------|-------------| @@ -107,10 +181,10 @@ Ask: "How do you want to deliver the sprite atlases?" | Localized UI sprites (multiple languages) | **Option B: Addressables** | | Character skins or cosmetics | **Option B: Addressables** | -### 2. SpritePacker Mode (REQUIRED) +### 4. SpritePacker Mode (REQUIRED) **Enable Sprite Packer mode before creating atlases, then read the setting back and confirm it took.** -Use the code in [resources/enablespritepacking.cs](resources/enablespritepacking.cs); it sets +Use the code in [scripts/enablespritepacking.cs](scripts/enablespritepacking.cs); it sets `EditorSettings.spritePackerMode` and configures the importer's packing settings. This is the step that decides whether the atlas you produce is real. `Disabled` is the zero value of @@ -126,71 +200,11 @@ say so rather than assuming the write landed. **DO NOT edit meta files DIRECTLY.** -## 🚨 CRITICAL: Default Approach is Prebuild Generation - -**ALWAYS use `IPreprocessBuildWithReport` to automatically generate or update SpriteAtlases during the build pipeline.** This is the DEFAULT and REQUIRED approach unless the user EXPLICITLY requests manual authoring. - -### ❌ DO NOT Create Manual Menu Item Scripts - -**NEVER create scripts with `[MenuItem]` attributes for atlas generation unless explicitly requested.** The prebuild approach eliminates the need for manual clicks. **Only use manual authoring for**: Hand-optimized layouts, specific sprite arrangements, or editor preview requirements. See [Advanced: Manual Authoring](#advanced-manual-authoring). - -## 🚨 CRITICAL: Sprite Source Location Restriction - -**ONLY add sprites from the project's Assets folder. NEVER add sprites from Unity built-in assets, packages, or external locations.** Unity built-in assets cannot be packed into SpriteAtlas, and package assets may cause import/dependency issues. - -## Critical V2 Architecture - -| Context | Component | Purpose | Allowed Usage | -|---------|-----------|---------|---------------| -| **Editor Authoring** | `SpriteAtlasAsset` | Add/remove sprites/folders; store metadata | ✅ Editor scripts only | -| **Editor Settings** | `SpriteAtlasImporter` | Configure texture, packing, platform settings | ✅ Editor scripts only | -| **Editor Packing** | `SpriteAtlasUtility.PackAtlases()` | *Optional* editor preview packing (not for build) | ⚠ Only for preview; atlases auto-pack at build | -| **Runtime** | `SpriteAtlas` | Query packed sprites (read-only) | ✅ Runtime scripts only | -| **Runtime Loading** | `SpriteAtlasManager` | Dynamic loading callbacks | ✅ Runtime scripts only | - -### Forbidden Cross-Context Usage (Common Error Sources) - -| ❌ Invalid Pattern | ✅ Correct Pattern | -|--------------------|-------------------| -| `new SpriteAtlas()` in editor code | Use `SpriteAtlasAsset` + `SpriteAtlasImporter` | -| `AssetDatabase.LoadAssetAtPath<SpriteAtlas>(...)` in editor | Use `SpriteAtlasAsset.Load(...)` | -| `SpriteAtlasAsset.GetPackables()` in editor | Use `SpriteAtlas.GetPackables()` | -| Modifying `SpriteAtlas` in editor scripts | Modify `SpriteAtlasAsset` → reimport → use `SpriteAtlasImporter` | -| Create variants from original packable objects (sprites/folders) | Creating variants from a Master runtime `SpriteAtlas` | +### 5. Create Prebuild Script -**NEVER script against `SpriteAtlas` in editor code** — it is *only* for runtime use in V2 except for GetPackables. - -## Core V2 Workflow (Reference Only - Use Prebuild Instead) - -> 🚨 **IMPORTANT**: This workflow is shown for reference only. **ALWAYS implement this inside `IPreprocessBuildWithReport.OnPreprocessBuild()`** rather than in manual scripts. See [Quick Start](#quick-start-automated-prebuild-generation-default-approach). - -## Prerequisites - -- Unity 6000.3 or later -- Basic understanding of Unity's asset import pipeline -- Familiarity with editor scripting for atlas authoring - -## Quick Start: Automated Prebuild Generation (DEFAULT APPROACH) - -### Overview - -**This is the PRIMARY and DEFAULT way to create SpriteAtlases.** Implement `IPreprocessBuildWithReport` to automatically generate or update SpriteAtlases before each build based on categorization rules. No manual menu clicks required. - -### Workflow Steps - -**Step 1: Ask User for Delivery Mechanism** - -Before generating code, ask: "How do you want to deliver the sprite atlases: (A) Built-in data or (B) Late-binding via Addressables?" - -**Step 2: Create Prebuild Script** - -Create this script in an Editor folder. Customize based on user's delivery choice: - -### Option A: Built-in Data (Immediate Loading) +Create this script in an Editor folder. Customize based on user's delivery choice. For Option A, generate 1 script: the prebuild generator (`includeInBuild = true`). -Built-in Data (Immediate Loading) - -### Option B: Late-Binding via Addressables (On-Demand Loading) +#### Option B: Late-Binding via Addressables (On-Demand Loading) > 🚨 **CRITICAL ENFORCEMENT**: When user chooses Addressables, you MUST generate ALL THREE scripts below. Never generate just one or two - all three are required for Addressables delivery to work. @@ -204,34 +218,9 @@ See [references/addressables-delivery.md](references/addressables-delivery.md) f #### Complete Workflow -``` -User Request - ↓ -Step 0: Check for existing scripts with [UNITY-SKILL:SPRITEATLAS] identifier - ↓ - ├─ Found existing scripts? - │ ↓ YES - │ Ask user: Update existing / Create new / Abort - │ ↓ - │ Handle user choice - │ - └─ NO existing scripts or user chose "Create new" - ↓ - Ask "Built-in data or Addressables?" - ↓ - ├─ Option A: Built-in - │ ↓ - │ Generate 1 script: Prebuild generator (includeInBuild=true) - │ - └─ Option B: Addressables - ↓ - Generate 3 scripts: - 1. Prebuild: Generate atlases + create Addressables entries (includeInBuild=false) - 2. Postprocess: Build Addressables bundles - 3. Runtime: Late-binding loader component -``` - -**Step 3: Customize Categorization Rules** +The decision flow from step 2 through script generation is in [references/workflow.md](references/workflow.md). + +### 6. Customize Categorization Rules Edit the `OnPreprocessBuild` method to match your project's sprite organization. Choose one or combine multiple strategies: @@ -242,110 +231,44 @@ Edit the `OnPreprocessBuild` method to match your project's sprite organization. | **Asset labels** | Sprites tagged with labels | | **Scene-based** | Sprites used in specific scenes | Query scene references | -**Step 4: Build Your Project** +### 7. Build Your Project Atlases are automatically generated/updated during build. **No manual menu clicks required.** This is why prebuild is the default approach. -**For Built-in Data (Option A):** -- Atlases are included in build -- Ready for immediate use at runtime +For Option B, the build also creates the Addressables entries and builds the content bundles, using the three scripts from step 5. At runtime, the late-binding loader loads each atlas when its sprites are first accessed. -**For Addressables (Option B) - Additional Required Steps:** +### Common Categorization Patterns -You MUST generate THREE scripts (not just one): +Read [references/categorization-patterns.md](references/categorization-patterns.md) for common ways to group sprites into atlases. -1. **Prebuild script** (IPreprocessBuildWithReport) - Generates atlases and creates Addressables entries automatically -2. **Build Addressables script** (IPostprocessBuildWithReport) - Builds Addressables content bundles -3. **Late-binding runtime loader** (MonoBehaviour) - Handles on-demand loading via SpriteAtlasManager - -The build process will: -- Generate atlases (prebuild step) -- Create addressable entries automatically -- Build addressables content bundles (postprocess step) -- At runtime: Late-binding loader automatically loads atlases when sprites are first accessed +## Advanced: Manual Authoring (NOT Default - Use Only When Explicitly Requested) -### Common Categorization Patterns +Use manual authoring only when the user EXPLICITLY requests manual control or editor preview; otherwise use the [Procedure](#procedure). When it applies, and the patterns for master atlas creation, variant creation, and runtime loading, are in [references/manual-authoring.md](references/manual-authoring.md). -**By Folder Structure:** -```csharp -GenerateAtlasByFolder("Assets/Art/UI/Buttons", "Assets/Atlases/UI_Buttons.spriteatlasv2"); -GenerateAtlasByFolder("Assets/Art/UI/Icons", "Assets/Atlases/UI_Icons.spriteatlasv2"); -GenerateAtlasByFolder("Assets/Art/Characters/Player", "Assets/Atlases/Player.spriteatlasv2"); -``` +## Detailed Reference -**By Naming Convention:** -```csharp -GenerateAtlasByNaming("Assets/Art", "icon_", "Assets/Atlases/Icons.spriteatlasv2"); -GenerateAtlasByNaming("Assets/Art", "bg_", "Assets/Atlases/Backgrounds.spriteatlasv2"); -``` +- **Common Errors**: [references/common-errors.md](references/common-errors.md) - Error messages with their cause and fix +- **API Reference**: [references/api.md](references/api.md) - Script Reference page for each V2 type, API pitfalls, and the `using` directives editor and runtime scripts need. Read it before you generate code. +- **Custom Packing**: [references/custom-packing.md](references/custom-packing.md) - `ScriptablePacker` implementation +- **Best Practices**: [references/best-practices.md](references/best-practices.md) - Optimization and common pitfalls -### Variant Generation in Prebuild +## Final step -Generate variant atlases for different resolutions. +Do the following checks: -## Advanced: Manual Authoring (NOT Default - Use Only When Explicitly Requested) +1. Check the project has zero console errors. Use `console status` for counts. +2. Check each atlas you created or changed actually packs, because an atlas can import cleanly and still hold no sprites. In one `script eval`, load the atlas with `UnityEditor.AssetDatabase.LoadAssetAtPath<UnityEngine.U2D.SpriteAtlas>(path)`, pack it with `UnityEditor.U2D.SpriteAtlasUtility.PackAtlases(new[] { atlas }, UnityEditor.EditorUserBuildSettings.activeBuildTarget, false)`, and return `atlas.spriteCount` and `atlas.CanBindTo(sprite)` for one sprite you added. These calls only read the atlas and write the packing cache, so they don't break the editor/runtime split. The check passes when `spriteCount` is greater than zero and `CanBindTo` returns `true`. +3. Stop there unless the user asked you to prove it works or you suspect a specific fault. +4. If you do enter Play mode, do it once only to chase a fault you already suspect. Read the world through `script eval` rather than adding logging. Take no screenshots as they take too much time. -> ⚠ **WARNING**: Manual authoring is NOT the default approach. Only use these patterns when the user EXPLICITLY requests manual control or editor preview during development. - -> 🚨 **DEFAULT APPROACH**: Use prebuild generation with `IPreprocessBuildWithReport` instead. See [Quick Start](#quick-start-automated-prebuild-generation-default-approach). - -**Manual authoring is appropriate ONLY for:** -- Hand-optimized sprite layouts where exact positioning matters -- Custom sprite ordering requirements -- Editor preview during authoring workflow -- Explicitly requested by user - -**DO NOT use manual authoring when:** -- User asks to "create sprite atlas" (use prebuild) -- User asks to "optimize sprites" (use prebuild) -- User asks for automated workflow (use prebuild) -- No specific manual control requirement mentioned - -For complete manual authoring patterns including master atlas creation, variant creation, and runtime loading, see [references/manual-authoring.md](references/manual-authoring.md). - -## Key Requirements (V2-Specific) - -1. **🚨 ALWAYS check for existing scripts FIRST**: Before generating code, scan for scripts with `[UNITY-SKILL:SPRITEATLAS]` identifier and prompt user to update or create new -2. **🚨 ALWAYS tag generated scripts**: Include skill identifier at the top of every generated script for future detection -3. **🚨 ALWAYS ask for delivery mechanism**: Ask user "Built-in data or Addressables?" before generating code -4. **🚨 ALWAYS enable Sprite Packer mode**: Set `EditorSettings.spritePackerMode = SpritePackerMode.SpriteAtlasV2` in prebuild script -5. **🚨 ALWAYS use prebuild generation**: Implement `IPreprocessBuildWithReport` as the DEFAULT approach for creating atlases -6. **🚨 ONLY add sprites from Assets/ folder**: Never add sprites from Packages, built-in assets, or external locations -7. **🚨 For Addressables delivery, ALWAYS generate THREE scripts**: - - Prebuild atlas generator with Addressables setup - - `IPostprocessBuildWithReport` to build Addressables content - - Late-binding runtime loader script (extends `SpriteAtlasManager`) -8. **Set includeInBuild correctly**: `true` for built-in data, `false` for Addressables -9. **Two-Step Editor Pattern**: Create with `SpriteAtlasAsset` → Save → Import → Configure via `SpriteAtlasImporter` → SaveAndReimport() -10. **Never use `SpriteAtlas` in editor code** — except `SpriteAtlas.GetPackables()` instance method on a loaded runtime atlas -11. **Variants reference master**: Use `SetMasterAtlas(SpriteAtlas)` with runtime instance loaded via `AssetDatabase.LoadAssetAtPath<SpriteAtlas>()` -12. **Platform format assignment**: Use `format = TextureImporterFormat.ASTC_6x6` directly (no cast) -13. **File extension**: V2 atlases use `.spriteatlasv2` (not `.spriteatlas`) -14. **`SpriteAtlasUtility.PackAtlases()` is optional**: Only for editor preview; build-time packing is automatic - -For common errors and invalid patterns, see [references/common-errors.md](references/common-errors.md). +If a check fails, go back and reread the [docs pages](#full-topic-map) to find out what you missed. If `spriteCount` is zero, read `EditorSettings.spritePackerMode` again first, because a `Disabled` packer mode is the most common cause. -## Detailed Reference +## Final report -- **Addressables Delivery**: [references/addressables-delivery.md](references/addressables-delivery.md) - Complete late-binding setup with Addressables -- **Manual Authoring**: [references/manual-authoring.md](references/manual-authoring.md) - Manual patterns (NOT default - use only when explicitly requested) -- **Common Errors**: [references/common-errors.md](references/common-errors.md) - Invalid patterns and API corrections -- **API Reference**: [references/api.md](references/api.md) - Complete V2 class documentation -- **Custom Packing**: [references/custom-packing.md](references/custom-packing.md) - `ScriptablePacker` implementation -- **Best Practices**: [references/best-practices.md](references/best-practices.md) - Optimization and common pitfalls +Give the user a concise but not dense checklist that includes: -## Namespaces - -**Editor Scripts:** -```csharp -using UnityEditor; // AssetImporter, AssetDatabase -using UnityEditor.U2D; // SpriteAtlasAsset, SpriteAtlasImporter, SpriteAtlasUtility -using UnityEngine; // Runtime types (e.g., TextureImporterFormat) -using UnityEngine.U2D; // SpriteAtlas -``` - -**Runtime Scripts:** -```csharp -using UnityEngine; // Core Unity types -using UnityEngine.U2D; // SpriteAtlas, SpriteAtlasManager -``` +- The scripts you created or updated, with their paths, and the delivery option they implement. +- The `EditorSettings.spritePackerMode` value you read back. +- The checks you ran and their results, including the `spriteCount` you read. +- Any incidental side effects, for example `EditorSettings` values you changed or atlases you packed to verify them. +- Any follow-up the user needs to do, such as installing Addressables or building the project. diff --git a/skills/using-unity/references/manage-sprite-atlas/references/addressables-delivery.md b/skills/using-unity/references/manage-sprite-atlas/references/addressables-delivery.md index 4cf2f2b..c7ab9cf 100644 --- a/skills/using-unity/references/manage-sprite-atlas/references/addressables-delivery.md +++ b/skills/using-unity/references/manage-sprite-atlas/references/addressables-delivery.md @@ -1,4 +1,5 @@ # Late-Binding via Addressables (On-Demand Loading) +Relative paths in this file resolve to the skill directory — the folder that holds the skill's main instructions. This approach creates SpriteAtlases that are NOT included in the build and are instead loaded on-demand via the Addressables system. @@ -25,19 +26,19 @@ When using Addressables, you MUST create all three scripts: ## Script 1: Prebuild Atlas Generator with Addressables -See [resources/spriteatlasprebuildgenerator.cs](../resources/spriteatlasprebuildgenerator.cs). +See [scripts/spriteatlasprebuildgenerator.cs](../scripts/spriteatlasprebuildgenerator.cs). ## Script 2: Build Addressables Content (REQUIRED) This script runs AFTER atlas generation to build the Addressables content bundle. -See [resources/buildaddressablespostprocess.cs](../resources/buildaddressablespostprocess.cs). +See [scripts/buildaddressablespostprocess.cs](../scripts/buildaddressablespostprocess.cs). ## Script 3: Late-Binding Runtime Loader (REQUIRED) This script handles automatic on-demand loading of atlases via SpriteAtlasManager callbacks. -See [resources/spriteatlaslatebinding.cs](../resources/spriteatlaslatebinding.cs). +See [scripts/spriteatlaslatebinding.cs](../scripts/spriteatlaslatebinding.cs). ## Setup Instructions diff --git a/skills/using-unity/references/manage-sprite-atlas/references/api.md b/skills/using-unity/references/manage-sprite-atlas/references/api.md index 144abcb..4e4c728 100644 --- a/skills/using-unity/references/manage-sprite-atlas/references/api.md +++ b/skills/using-unity/references/manage-sprite-atlas/references/api.md @@ -1,382 +1,76 @@ -# SpriteAtlas V2 API Reference +# SpriteAtlas V2 API -Complete API documentation for Unity's SpriteAtlas V2 system. +Where to read each V2 type's Script Reference page, and the API rules a model is likely to get wrong. -## Table of Contents - -- [SpriteAtlasAsset (Editor Authoring)](#spriteatlasasset-editor-authoring) -- [SpriteAtlasImporter (Editor Settings)](#spriteatlasimporter-editor-settings) -- [SpriteAtlasUtility (Editor Packing)](#spriteatlasutility-editor-packing) -- [SpriteAtlas (Runtime)](#spriteatlas-runtime) -- [SpriteAtlasManager (Runtime Loading)](#spriteatlasmanager-runtime-loading) -- [Settings Structures](#settings-structures) - -## SpriteAtlasAsset (Editor Authoring) - -**Namespace:** `UnityEditor.U2D` -**Location:** `SpriteAtlasAsset.bindings.cs` - -Primary API for adding/removing content from sprite atlases. - -### Constructor - -```csharp -SpriteAtlasAsset atlasAsset = new SpriteAtlasAsset(); -``` - -### Content Management - -```csharp -// Add sprites or folders -void Add(Object[] objects) - -// Remove packables -void Remove(Object[] objects) - -// Remove by index -void RemoveAt(int index) -``` - -### Persistence - -```csharp -// Save to disk -static void Save(SpriteAtlasAsset asset, string path) - -// Load from disk -static SpriteAtlasAsset Load(string path) -``` - -### Variant Configuration - -```csharp -// Mark as variant atlas -void SetIsVariant(bool value) - -// Check if variant -bool isVariant { get; } - -// Set master atlas (requires SpriteAtlas reference) -void SetMasterAtlas(SpriteAtlas master) - -// Get master atlas -SpriteAtlas GetMasterAtlas() -``` - -### Custom Packer - -```csharp -// Set custom packing algorithm -void SetScriptablePacker(Object packer) - -// Get current packer -Object GetPacker() -``` - -### Deprecated Methods - -These methods are deprecated in V2. Use `SpriteAtlasImporter` instead: - -- `SetVariantScale()` → Use `SpriteAtlasImporter.variantScale` -- `SetIncludeInBuild()` → Use `SpriteAtlasImporter.includeInBuild` -- `IsIncludeInBuild()` → Use `SpriteAtlasImporter.includeInBuild` -- `SetPlatformSettings()` → Use `SpriteAtlasImporter.SetPlatformSettings()` -- `SetTextureSettings()` → Use `SpriteAtlasImporter.textureSettings` -- `SetPackingSettings()` → Use `SpriteAtlasImporter.packingSettings` - -## SpriteAtlasImporter (Editor Settings) - -**Namespace:** `UnityEditor.U2D` -**Location:** `SpriteAtlasImporter.bindings.cs` - -Primary API for configuring all sprite atlas settings. - -### Getting the Importer - -```csharp -string path = "Assets/MyAtlas.spriteatlas"; -SpriteAtlasImporter importer = AssetImporter.GetAtPath(path) as SpriteAtlasImporter; -``` - -### Basic Properties - -```csharp -// Variant scale multiplier -float variantScale { get; set; } - -// Include atlas in player build -bool includeInBuild { get; set; } -``` - -### Texture Settings - -```csharp -// Get/set texture settings (struct) -SpriteAtlasTextureSettings textureSettings { get; set; } - -// Example: -SpriteAtlasTextureSettings settings = importer.textureSettings; -settings.filterMode = FilterMode.Bilinear; -settings.generateMipMaps = false; -settings.readable = false; -settings.sRGB = true; -importer.textureSettings = settings; -``` - -### Packing Settings - -```csharp -// Get/set packing settings (struct) -SpriteAtlasPackingSettings packingSettings { get; set; } - -// Example: -SpriteAtlasPackingSettings settings = importer.packingSettings; -settings.padding = 4; -settings.enableRotation = false; -settings.enableTightPacking = false; -settings.enableAlphaDilation = true; -importer.packingSettings = settings; -``` - -### Platform Settings - -```csharp -// Get platform-specific settings -TextureImporterPlatformSettings GetPlatformSettings(string platform) - -// Set platform-specific settings -void SetPlatformSettings(TextureImporterPlatformSettings settings) - -// Example: -TextureImporterPlatformSettings platformSettings = importer.GetPlatformSettings("Android"); -platformSettings.overridden = true; -platformSettings.maxTextureSize = 2048; -platformSettings.format = TextureImporterFormat.ASTC_6x6; -platformSettings.compressionQuality = 50; -importer.SetPlatformSettings(platformSettings); -``` - -Platform names: "Standalone", "Android", "iOS", "WebGL", etc. - -### Applying Changes +Relative paths in this file resolve to the skill directory. -```csharp -// REQUIRED: Save and reimport after any changes -void SaveAndReimport() -``` - -**Critical:** Always call `SaveAndReimport()` after modifying importer properties. - -## SpriteAtlasUtility (Editor Packing) - -**Namespace:** `UnityEditor.U2D` -**Location:** `EditorSpritePacking.bindings.cs` - -Utilities for packing sprite atlases. - -### Packing Operations - -```csharp -// Pack all atlases in project for target platform -static void PackAllAtlases(BuildTarget target, bool canCancel) - -// Pack specific atlases -static void PackAtlases(SpriteAtlas[] atlases, BuildTarget target, bool canCancel) - -// Clean up packing temporary data -static void CleanupAtlasPacking() -``` - -### Usage - -```csharp -using UnityEditor; -using UnityEditor.U2D; - -BuildTarget target = EditorUserBuildSettings.activeBuildTarget; - -// Pack all -SpriteAtlasUtility.PackAllAtlases(target, canCancel: true); -SpriteAtlasUtility.CleanupAtlasPacking(); - -// Pack specific -SpriteAtlas[] atlases = new[] { atlas1, atlas2 }; -SpriteAtlasUtility.PackAtlases(atlases, target, canCancel: false); -SpriteAtlasUtility.CleanupAtlasPacking(); -``` - -**Important:** Always call `CleanupAtlasPacking()` after batch packing operations. - -## SpriteAtlas (Runtime) - -**Namespace:** `UnityEngine.U2D` -**Location:** `Runtime/2D/SpriteAtlas/ScriptBindings/SpriteAtlas.bindings.cs` - -**RUNTIME ONLY** - Do not script against SpriteAtlas in editor code. Provides read-only access to packed sprites. - -### Properties - -```csharp -// Total sprite count in atlas -int spriteCount { get; } - -// Atlas tag identifier -string tag { get; } - -// Check if atlas is variant -bool isVariant { get; } -``` - -### Sprite Queries - -```csharp -// Get sprite by name -Sprite GetSprite(string name) - -// Get all sprites -int GetSprites(Sprite[] sprites) - -// Get sprites matching name prefix -int GetSprites(Sprite[] sprites, string namePrefix) - -// Check if sprite belongs to atlas -bool CanBindTo(Sprite sprite) -``` - -### Usage - -```csharp -using UnityEngine; -using UnityEngine.U2D; - -SpriteAtlas atlas = Resources.Load<SpriteAtlas>("MyAtlas"); - -// Get specific sprite -Sprite sprite = atlas.GetSprite("SpriteName"); - -// Get all sprites -Sprite[] allSprites = new Sprite[atlas.spriteCount]; -int count = atlas.GetSprites(allSprites); - -// Get sprites with prefix -Sprite[] enemySprites = new Sprite[atlas.spriteCount]; -int enemyCount = atlas.GetSprites(enemySprites, "Enemy_"); - -// Validate sprite binding -bool canBind = atlas.CanBindTo(sprite); -``` - -## SpriteAtlasManager (Runtime Loading) - -**Namespace:** `UnityEngine.U2D` -**Location:** `Runtime/2D/SpriteAtlas/ScriptBindings/SpriteAtlas.bindings.cs` - -Manages atlas loading callbacks and runtime creation. - -### Events - -```csharp -// Called when an atlas is requested (late binding) -static event Action<string, Action<SpriteAtlas>> atlasRequested - -// Called when an atlas is registered -static event Action<SpriteAtlas> atlasRegistered -``` - -### Late Binding Pattern +## Table of Contents -```csharp -using UnityEngine; -using UnityEngine.U2D; +- [Script Reference pages](#script-reference-pages) +- [Deprecated SpriteAtlasAsset methods](#deprecated-spriteatlasasset-methods) +- [Key Requirements (V2-Specific)](#key-requirements-v2-specific) +- [Namespaces](#namespaces) -public class AtlasLoader : MonoBehaviour -{ - void OnEnable() - { - SpriteAtlasManager.atlasRequested += OnAtlasRequested; - SpriteAtlasManager.atlasRegistered += OnAtlasRegistered; - } +## Script Reference pages - void OnDisable() - { - SpriteAtlasManager.atlasRequested -= OnAtlasRequested; - SpriteAtlasManager.atlasRegistered -= OnAtlasRegistered; - } +Read the page for each type before you write code against it, because member names and overloads change between Unity versions. Each entry gives the local file under `<editor-install>/Editor/Data/Documentation/en/ScriptReference/` and the online page. Replace `<VERSION>` with the project's Unity version, as described in the Full topic map of the skill. - void OnAtlasRequested(string tag, System.Action<SpriteAtlas> callback) - { - // Load atlas from Resources or AssetBundle - SpriteAtlas atlas = Resources.Load<SpriteAtlas>($"Atlases/{tag}"); - callback(atlas); - } +- **SpriteAtlasAsset** (editor authoring: add and remove packables, save, load, variants, custom packer) — local `U2D.SpriteAtlasAsset.html`, online `https://docs.unity.com/en-us/engine/<VERSION>/script-reference/unityeditor/u2d/spriteatlasasset.md` +- **SpriteAtlasImporter** (editor settings: texture, packing, platform, `includeInBuild`, `variantScale`) — local `U2D.SpriteAtlasImporter.html`, online `https://docs.unity.com/en-us/engine/<VERSION>/script-reference/unityeditor/u2d/spriteatlasimporter.md` +- **SpriteAtlasUtility** (editor preview packing) — local `U2D.SpriteAtlasUtility.html`, online `https://docs.unity.com/en-us/engine/<VERSION>/script-reference/unityeditor/u2d/spriteatlasutility.md` +- **SpriteAtlasExtensions** (editor extension methods on `SpriteAtlas`, including `GetPackables`) — local `U2D.SpriteAtlasExtensions.html`, online `https://docs.unity.com/en-us/engine/<VERSION>/script-reference/unityeditor/u2d/spriteatlasextensions.md` +- **SpriteAtlas** (runtime sprite queries) — local `U2D.SpriteAtlas.html`, online `https://docs.unity.com/en-us/engine/<VERSION>/script-reference/unityengine/u2d/spriteatlas.md` +- **SpriteAtlasManager** (runtime late-binding events) — local `U2D.SpriteAtlasManager.html`, online `https://docs.unity.com/en-us/engine/<VERSION>/script-reference/unityengine/u2d/spriteatlasmanager.md` +- **TextureImporterPlatformSettings** (per-platform overrides passed to `SpriteAtlasImporter.SetPlatformSettings`) — local `TextureImporterPlatformSettings.html`, online `https://docs.unity.com/en-us/engine/<VERSION>/script-reference/unityeditor/textureimporterplatformsettings.md` - void OnAtlasRegistered(SpriteAtlas atlas) - { - Debug.Log($"Atlas registered: {atlas.tag}"); - } -} -``` +For which compression formats each platform supports, read the **Choose a GPU texture format by platform** page in [docs-map.md](docs-map.md) rather than guessing. -### Runtime Atlas Creation +## Deprecated SpriteAtlasAsset methods -```csharp -// Create atlas at runtime -static SpriteAtlas CreateSpriteAtlas(string name, - SpriteAtlasRuntimeConfig config, - AtlasPage[] pages) -``` +These `SpriteAtlasAsset` setters are deprecated in V2. Use the `SpriteAtlasImporter` member instead, because the importer is what the build reads: -Advanced usage for dynamic atlas generation. See custom-packing.md for details. +| Deprecated | Use instead | +|---|---| +| `SetVariantScale()` | `SpriteAtlasImporter.variantScale` | +| `SetIncludeInBuild()`, `IsIncludeInBuild()` | `SpriteAtlasImporter.includeInBuild` | +| `SetPlatformSettings()` | `SpriteAtlasImporter.SetPlatformSettings()` | +| `SetTextureSettings()` | `SpriteAtlasImporter.textureSettings` | +| `SetPackingSettings()` | `SpriteAtlasImporter.packingSettings` | -## Settings Structures +## Key Requirements (V2-Specific) -### SpriteAtlasTextureSettings +1. **🚨 ALWAYS check for existing scripts FIRST**: Before generating code, scan for scripts with `[UNITY-SKILL:SPRITEATLAS]` identifier and prompt user to update or create new +2. **🚨 ALWAYS tag generated scripts**: Include skill identifier at the top of every generated script for future detection +3. **🚨 ALWAYS ask for delivery mechanism**: Ask user "Built-in data or Addressables?" before generating code +4. **🚨 ALWAYS enable Sprite Packer mode**: Set `EditorSettings.spritePackerMode = SpritePackerMode.SpriteAtlasV2` in prebuild script +5. **🚨 ALWAYS use prebuild generation**: Implement `IPreprocessBuildWithReport` as the DEFAULT approach for creating atlases +6. **🚨 ONLY add sprites from Assets/ folder**: Never add sprites from Packages, built-in assets, or external locations +7. **🚨 For Addressables delivery, ALWAYS generate THREE scripts**: + - Prebuild atlas generator with Addressables setup + - `IPostprocessBuildWithReport` to build Addressables content + - Late-binding runtime loader script that subscribes to `SpriteAtlasManager.atlasRequested` +8. **Set includeInBuild correctly**: `true` for built-in data, `false` for Addressables +9. **Two-Step Editor Pattern**: Create with `SpriteAtlasAsset` → Save → Import → Configure via `SpriteAtlasImporter` → SaveAndReimport(), because importer changes don't apply until the asset reimports +10. **Never use `SpriteAtlas` in editor code** — except `SpriteAtlas.GetPackables()` instance method on a loaded runtime atlas +11. **Variants reference master**: Use `SetMasterAtlas(SpriteAtlas)` with runtime instance loaded via `AssetDatabase.LoadAssetAtPath<SpriteAtlas>()` +12. **Platform format assignment**: Use `format = TextureImporterFormat.ASTC_6x6` directly (no cast) +13. **File extension**: V2 atlases use `.spriteatlasv2` (not `.spriteatlas`) +14. **`SpriteAtlasUtility.PackAtlases()` is optional**: Only for editor preview and verification; build-time packing is automatic -```csharp -struct SpriteAtlasTextureSettings -{ - int maxTextureSize { get; } // Read-only - int anisoLevel { get; set; } // Anisotropic filtering level - FilterMode filterMode { get; set; } // Point, Bilinear, Trilinear - bool generateMipMaps { get; set; } // Enable mipmap generation - bool readable { get; set; } // CPU-readable texture - bool sRGB { get; set; } // Use sRGB color space -} -``` +For common errors and invalid patterns, see [common-errors.md](common-errors.md). -### SpriteAtlasPackingSettings +## Namespaces +**Editor Scripts:** ```csharp -struct SpriteAtlasPackingSettings -{ - int blockOffset { get; set; } // Block offset for algorithm - int padding { get; set; } // Padding between sprites (pixels) - bool enableRotation { get; set; } // Allow sprite rotation - bool enableTightPacking { get; set; } // Pack around sprite meshes - bool enableAlphaDilation { get; set; } // Prevent bleeding artifacts -} +using UnityEditor; // AssetImporter, AssetDatabase, TextureImporterFormat +using UnityEditor.U2D; // SpriteAtlasAsset, SpriteAtlasImporter, SpriteAtlasUtility +using UnityEngine; // Core Unity types +using UnityEngine.U2D; // SpriteAtlas ``` -### TextureImporterPlatformSettings - -Used for platform-specific configuration. See Unity's `TextureImporter` documentation for complete reference. - -Common fields: +**Runtime Scripts:** ```csharp -class TextureImporterPlatformSettings -{ - string name { get; set; } // Platform name - bool overridden { get; set; } // Override default settings - int maxTextureSize { get; set; } // Max size (32-8192) - TextureImporterFormat format { get; set; } // Compression format - int compressionQuality { get; set; } // Quality (0-100) -} +using UnityEngine; // Core Unity types +using UnityEngine.U2D; // SpriteAtlas, SpriteAtlasManager ``` - -Common platform names: "Standalone", "Android", "iOS", "WebGL" - -Common formats: -- Android: `TextureImporterFormat.ASTC_6x6`, `TextureImporterFormat.ETC2_RGBA8` -- iOS: `TextureImporterFormat.ASTC_6x6`, `TextureImporterFormat.PVRTC_RGBA4` -- Desktop: `TextureImporterFormat.DXT5`, `TextureImporterFormat.BC7` -- WebGL: `TextureImporterFormat.DXT5` diff --git a/skills/using-unity/references/manage-sprite-atlas/references/best-practices.md b/skills/using-unity/references/manage-sprite-atlas/references/best-practices.md index cd612cf..7364920 100644 --- a/skills/using-unity/references/manage-sprite-atlas/references/best-practices.md +++ b/skills/using-unity/references/manage-sprite-atlas/references/best-practices.md @@ -1,4 +1,5 @@ # SpriteAtlas V2 Best Practices +Relative paths in this file resolve to the skill directory — the folder that holds the skill's main instructions. Optimization tips, common pitfalls, and recommended patterns for SpriteAtlas V2. @@ -53,81 +54,81 @@ Optimization tips, common pitfalls, and recommended patterns for SpriteAtlas V2. ### Always Use SpriteAtlasImporter for Configuration -See [resources/editorconfiguration.cs](../resources/editorconfiguration.cs). +See [scripts/editorconfiguration.cs](../scripts/editorconfiguration.cs). ### Save SpriteAtlasAsset Properly -See [resources/savespriteatlasasset.cs](../resources/savespriteatlasasset.cs). +See [scripts/savespriteatlasasset.cs](../scripts/savespriteatlasasset.cs). ### Clean Up After Batch Operations -See [resources/cleanupbatchoperations.cs](../resources/cleanupbatchoperations.cs). +See [scripts/cleanupbatchoperations.cs](../scripts/cleanupbatchoperations.cs). ### Handle Null Cases -See [resources/handlenullcases.cs](../resources/handlenullcases.cs). +See [scripts/handlenullcases.cs](../scripts/handlenullcases.cs). ### Use Correct Platform Names -See [resources/platformnames.cs](../resources/platformnames.cs). +See [scripts/platformnames.cs](../scripts/platformnames.cs). ## Runtime Code Best Practices ### Register Callbacks Early -See [resources/registercallbacks.cs](../resources/registercallbacks.cs). +See [scripts/registercallbacks.cs](../scripts/registercallbacks.cs). ### Cache Loaded Atlases -See [resources/cacheloadedatlases.cs](../resources/cacheloadedatlases.cs). +See [scripts/cacheloadedatlases.cs](../scripts/cacheloadedatlases.cs). ### Handle Late Binding Properly -See [resources/handlelatebinding.cs](../resources/handlelatebinding.cs). +See [scripts/handlelatebinding.cs](../scripts/handlelatebinding.cs). ### Query Sprites Efficiently -See [resources/queryspritesefficiently.cs](../resources/queryspritesefficiently.cs). +See [scripts/queryspritesefficiently.cs](../scripts/queryspritesefficiently.cs). ## Performance Best Practices ### Optimize Texture Settings -See [resources/optimizetexturesettings.cs](../resources/optimizetexturesettings.cs). +See [scripts/optimizetexturesettings.cs](../scripts/optimizetexturesettings.cs). ### Enable Tight Packing -See [resources/enablespritepacking.cs](../resources/enablespritepacking.cs). +See [scripts/enablespritepacking.cs](../scripts/enablespritepacking.cs). ### Use Variants Wisely -See [resources/usevariantswisely.cs](../resources/usevariantswisely.cs). +See [scripts/usevariantswisely.cs](../scripts/usevariantswisely.cs). ### Set includeInBuild Appropriately -See [resources/setincludeinbuild.cs](../resources/setincludeinbuild.cs). +See [scripts/setincludeinbuild.cs](../scripts/setincludeinbuild.cs). ## Common Pitfalls ### Don't Script SpriteAtlas in Editor -See [resources/dontscriptspriteatlasineditor.cs](../resources/dontscriptspriteatlasineditor.cs). +See [scripts/dontscriptspriteatlasineditor.cs](../scripts/dontscriptspriteatlasineditor.cs). ### Don't Use Deprecated SpriteAtlasAsset Methods -See [resources/deprecatedmethods.cs](../resources/deprecatedmethods.cs). +See [scripts/deprecatedmethods.cs](../scripts/deprecatedmethods.cs). ### Don't Pack in Runtime Builds -See [resources/dontpackinruntimebuilds.cs](../resources/dontpackinruntimebuilds.cs). +See [scripts/dontpackinruntimebuilds.cs](../scripts/dontpackinruntimebuilds.cs). ### Don't Modify Importer Without Saving -See [resources/dontmodifywithoutsaving.cs](../resources/dontmodifywithoutsaving.cs). +See [scripts/dontmodifywithoutsaving.cs](../scripts/dontmodifywithoutsaving.cs). ### Don't Confuse Authoring vs Runtime -See [resources/authoringvsruntime.cs](../resources/authoringvsruntime.cs). +See [scripts/authoringvsruntime.cs](../scripts/authoringvsruntime.cs). ## Migration from V1 to V2 @@ -135,15 +136,15 @@ If migrating from V1 code: ### Replace Direct SpriteAtlas Scripting -See [resources/migratev1tov2.cs](../resources/migratev1tov2.cs). +See [scripts/migratev1tov2.cs](../scripts/migratev1tov2.cs). ### Update Settings Configuration -See [resources/updatesettingsconfiguration.cs](../resources/updatesettingsconfiguration.cs). +See [scripts/updatesettingsconfiguration.cs](../scripts/updatesettingsconfiguration.cs). ### Update Build Scripts -See [resources/updatebuildscripts.cs](../resources/updatebuildscripts.cs). +See [scripts/updatebuildscripts.cs](../scripts/updatebuildscripts.cs). ## Checklist diff --git a/skills/using-unity/references/manage-sprite-atlas/references/categorization-patterns.md b/skills/using-unity/references/manage-sprite-atlas/references/categorization-patterns.md new file mode 100644 index 0000000..11a0f7a --- /dev/null +++ b/skills/using-unity/references/manage-sprite-atlas/references/categorization-patterns.md @@ -0,0 +1,14 @@ +# Common categorization patterns + +**By Folder Structure:** +```csharp +GenerateAtlasByFolder("Assets/Art/UI/Buttons", "Assets/Atlases/UI_Buttons.spriteatlasv2"); +GenerateAtlasByFolder("Assets/Art/UI/Icons", "Assets/Atlases/UI_Icons.spriteatlasv2"); +GenerateAtlasByFolder("Assets/Art/Characters/Player", "Assets/Atlases/Player.spriteatlasv2"); +``` + +**By Naming Convention:** +```csharp +GenerateAtlasByNaming("Assets/Art", "icon_", "Assets/Atlases/Icons.spriteatlasv2"); +GenerateAtlasByNaming("Assets/Art", "bg_", "Assets/Atlases/Backgrounds.spriteatlasv2"); +``` diff --git a/skills/using-unity/references/manage-sprite-atlas/references/common-errors.md b/skills/using-unity/references/manage-sprite-atlas/references/common-errors.md index b7e8d54..a26741d 100644 --- a/skills/using-unity/references/manage-sprite-atlas/references/common-errors.md +++ b/skills/using-unity/references/manage-sprite-atlas/references/common-errors.md @@ -1,123 +1,37 @@ # Common Errors and Invalid Patterns -This document covers invalid V2 patterns, API corrections, and common mistakes to avoid. +Errors that SpriteAtlas V2 scripts commonly hit, with their cause and fix. -## Table of Contents - -- [Invalid V2 Patterns (Do Not Use)](#invalid-v2-patterns-do-not-use) -- [Critical API Corrections](#critical-api-corrections) - - [❌ Format Casting in TextureImporterPlatformSettings](#-format-casting-in-textureimporterplatformsettings) - - [❌ SetMasterAtlasPath() - Method Does Not Exist](#-setmasteratlaspath---method-does-not-exist) - - [⚠ Platform-Specific Format Limitations](#-platform-specific-format-limitations) - - [⚠ PackAtlases() Requires Runtime SpriteAtlas[]](#-packatlases-requires-runtime-spriteatlas) - - [⚠ Always scope AssetDatabase.FindAssets to the folders you mean](#-always-scope-assetdatabasefindassets-to-the-folders-you-mean) - - [⚠ AssetImporter.GetAtPath() Takes Single Argument](#-assetimportergetatpath-takes-single-argument) - -## Invalid V2 Patterns (Do Not Use) - -```csharp -// ❌ WRONG - V1 pattern (scripting SpriteAtlas in editor) -SpriteAtlas atlas = new SpriteAtlas(); -atlas.Add(sprites); // Invalid in V2 -atlas.SetTextureSettings(settings); // Invalid in V2 - -// ❌ WRONG - Deprecated/invalid SpriteAtlasAsset methods -atlasAsset.SetTextureSettings(settings); // Use importer instead -atlasAsset.SetPackingSettings(settings); // Use importer instead -atlasAsset.SetIncludeInBuild(true); // Use importer instead - -// ❌ WRONG - Creating variants from runtime SpriteAtlas -SpriteAtlasAsset masterAsset = ...; -atlasVariant.Add(masterAsset.GetPackables()); // GetPackables() doesn't exist on SpriteAtlasAsset! - -// ❌ WRONG - Incorrect packable handling in variants -SpriteAtlasAsset variant = new SpriteAtlasAsset(); -variant.SetMasterAtlas(atlasPath); // WRONG: SetMasterAtlas expects a Runtime SpriteAtlas, not path or SpriteAtlasAsset! - -// ❌ WRONG - Format cast in TextureImporterPlatformSettings -var settings = new TextureImporterPlatformSettings { - format = (int)TextureImporterFormat.ASTC_6x6 // ❌ Explicit cast causes compile error -}; - -// ❌ WRONG - Using deprecated/invalid method -variant.SetMasterAtlasPath(path); // Method doesn't exist - use SetMasterAtlas() with runtime SpriteAtlas -``` - -## Critical API Corrections - -### ❌ Format Casting in TextureImporterPlatformSettings - -```csharp -// ❌ WRONG - Explicit cast causes compile error -var settings = new TextureImporterPlatformSettings { - format = (int)TextureImporterFormat.ASTC_6x6 -}; +Relative paths in this file resolve to the skill directory — the folder that holds the skill's main instructions. -// ✅ CORRECT - Direct enum assignment -var settings = new TextureImporterPlatformSettings { - format = TextureImporterFormat.ASTC_6x6 -}; -``` - -### ❌ SetMasterAtlasPath() - Method Does Not Exist - -```csharp -// ❌ WRONG - Method doesn't exist -variant.SetMasterAtlasPath(path); - -// ✅ CORRECT - Load runtime SpriteAtlas and pass to SetMasterAtlas() -SpriteAtlas masterRuntime = AssetDatabase.LoadAssetAtPath<SpriteAtlas>(masterPath); -variant.SetMasterAtlas(masterRuntime); -``` - -### ⚠ Platform-Specific Format Limitations - -- **PVRTC is NOT supported** in SpriteAtlas V2 -- Use **ASTC** for Android (`ASTC_6x6`, `ASTC_4x4`) -- Use **ASTC or ETC2** for iOS (`ASTC_4x4`, `ETC2_RGBA8`) -- Use **ETC2** for desktop (`ETC2_RGBA8`) - -### ⚠ PackAtlases() Requires Runtime SpriteAtlas[] - -```csharp -// ❌ WRONG - Passing SpriteAtlasAsset[] causes compilation error -SpriteAtlasUtility.PackAtlases(atlasAssets, ...); - -// ✅ CORRECT - Load runtime SpriteAtlases first -SpriteAtlas[] atlases = AssetDatabase.FindAssets("t:SpriteAtlas", new[] { "Assets" }) - .Select(g => AssetDatabase.LoadAssetAtPath<SpriteAtlas>(AssetDatabase.GUIDToAssetPath(g))) - .Where(a => a != null) - .ToArray(); -SpriteAtlasUtility.PackAtlases(atlases, EditorUserBuildSettings.activeBuildTarget, false); -``` - -### ⚠ Always scope AssetDatabase.FindAssets to the folders you mean - -```csharp -// ❌ WRONG - does not compile. There is no SearchMode overload. -string[] guids = AssetDatabase.FindAssets("t:SpriteAtlas", SearchMode.AllAssets); +## Table of Contents -// ❌ RISKY - compiles, but searches the WHOLE project including read-only packages -string[] guids = AssetDatabase.FindAssets("t:SpriteAtlas"); +- [Errors with a message](#errors-with-a-message) +- [Mistakes with no error message](#mistakes-with-no-error-message) -// ✅ CORRECT - the second parameter is string[] searchInFolders -string[] guids = AssetDatabase.FindAssets("t:SpriteAtlas", new[] { "Assets" }); -``` +## Errors with a message -`AssetDatabase.FindAssets` has exactly two overloads, `FindAssets(string filter)` and -`FindAssets(string filter, string[] searchInFolders)`. Verified on Unity 6000.5.8f1. +Match the message the Console or compiler shows against the first column. Compiler messages start with the code shown, followed by the member names from the user's code. -Scoping matters because an unscoped search reaches into `Packages/`, and those assets are usually -read-only. Measured on a real project: an unscoped `t:Scene` search returned 20 scenes where the -project itself has 1, and all 19 extras were package test fixtures. A batch operation that then -writes to what it found will fail, or worse, target assets it must not modify. +| Error message | Root cause | Fix | +|---|---|---| +| Inspector: `Sprite Atlas packing is disabled` | `EditorSettings.spritePackerMode` is `Disabled`, its default value | Set it to `SpritePackerMode.SpriteAtlasV2` with [scripts/enablespritepacking.cs](../scripts/enablespritepacking.cs), then read it back | +| `CS0266: Cannot implicitly convert type 'int' to 'UnityEditor.TextureImporterFormat'. An explicit conversion exists (are you missing a cast?)` | `format = (int)TextureImporterFormat.ASTC_6x6` casts the enum to `int` | Assign the enum directly: `format = TextureImporterFormat.ASTC_6x6` | +| `CS1061: 'SpriteAtlasAsset' does not contain a definition for 'SetMasterAtlasPath'` | `SetMasterAtlasPath` doesn't exist | Load the master with `AssetDatabase.LoadAssetAtPath<SpriteAtlas>(masterPath)` and pass it to `SetMasterAtlas` | +| `CS1503: Argument 1: cannot convert from 'string' to 'UnityEngine.U2D.SpriteAtlas'` on `SetMasterAtlas` | `SetMasterAtlas` takes the runtime `SpriteAtlas`, not a path or a `SpriteAtlasAsset` | Load the master as `SpriteAtlas` first, then pass that instance | +| `CS1929: 'SpriteAtlasAsset' does not contain a definition for 'GetPackables' and the best extension method overload 'SpriteAtlasExtensions.GetPackables(SpriteAtlas)' requires a receiver of type 'SpriteAtlas'` | `GetPackables` is an extension method on the runtime `SpriteAtlas`, not on `SpriteAtlasAsset` | Load the master as `SpriteAtlas` and call `GetPackables()` on it | +| `CS1503: Argument 1: cannot convert from 'UnityEditor.U2D.SpriteAtlasAsset[]' to 'UnityEngine.U2D.SpriteAtlas[]'` on `PackAtlases` | `SpriteAtlasUtility.PackAtlases` takes runtime `SpriteAtlas[]` | Load each atlas with `AssetDatabase.LoadAssetAtPath<SpriteAtlas>(path)` and pass that array | +| `CS1501: No overload for method 'GetAtPath' takes 2 arguments` | `AssetImporter.GetAtPath` takes only a path | Call `AssetImporter.GetAtPath(path) as SpriteAtlasImporter` | +| `CS0103: The name 'SearchMode' does not exist in the current context` on `AssetDatabase.FindAssets` | `FindAssets` has no `SearchMode` overload; the second parameter is `string[] searchInFolders` | Pass the folders to search: `AssetDatabase.FindAssets("t:SpriteAtlas", new[] { "Assets" })` | +| `CS0618: 'SpriteAtlasAsset.SetTextureSettings(SpriteAtlasTextureSettings)' is obsolete: 'SetTextureSettings is no longer supported and will be removed. Use SpriteAtlasImporter.SetTextureSettings instead.'` (same for `SetPackingSettings`, `SetIncludeInBuild`, `SetPlatformSettings`) | These `SpriteAtlasAsset` setters are deprecated in V2 | Set the matching `SpriteAtlasImporter` member, then call `SaveAndReimport()`. Despite the warning text, the importer exposes `textureSettings`, `packingSettings` and `includeInBuild` as properties, not `Set...` methods; only `SetPlatformSettings` is a method. The deprecated-methods table in the API reference file maps each one | -### ⚠ AssetImporter.GetAtPath() Takes Single Argument +## Mistakes with no error message -```csharp -// ❌ WRONG - No such overload -SpriteAtlasImporter importer = AssetImporter.GetAtPath(path, typeof(SpriteAtlasImporter)); +These compile and import cleanly, so check for them in the code you write. -// ✅ CORRECT - Single argument, cast result -SpriteAtlasImporter importer = AssetImporter.GetAtPath(path) as SpriteAtlasImporter; -``` +| Mistake | Why it matters | Fix | +|---|---|---| +| V1 pattern: `atlas.Add(...)` or other `SpriteAtlasExtensions` calls on a `SpriteAtlas` in editor code | These compile, because they resolve to the `SpriteAtlasExtensions` editor methods, so nothing warns you that you've bypassed V2 authoring | Author with `SpriteAtlasAsset` and configure with `SpriteAtlasImporter`. See [scripts/dontscriptspriteatlasineditor.cs](../scripts/dontscriptspriteatlasineditor.cs) | +| Unscoped `AssetDatabase.FindAssets("t:SpriteAtlas")` | It also searches `Packages/`, whose assets are read-only, so a batch write targets assets it must not modify | Always pass `new[] { "Assets" }` or the specific folders you mean | +| PVRTC formats in a V2 platform override | PVRTC is not supported in SpriteAtlas V2 | Use ASTC (`ASTC_4x4`, `ASTC_6x6`) for Android and iOS, or ETC2 (`ETC2_RGBA8`) for iOS | +| Importer properties changed without `SaveAndReimport()` | The change never reaches the imported atlas | Call `importer.SaveAndReimport()` after every change | diff --git a/skills/using-unity/references/manage-sprite-atlas/references/custom-packing.md b/skills/using-unity/references/manage-sprite-atlas/references/custom-packing.md index 36d49fc..40075c9 100644 --- a/skills/using-unity/references/manage-sprite-atlas/references/custom-packing.md +++ b/skills/using-unity/references/manage-sprite-atlas/references/custom-packing.md @@ -1,4 +1,5 @@ # Custom Sprite Packing with ScriptablePacker +Relative paths in this file resolve to the skill directory — the folder that holds the skill's main instructions. Guide for implementing custom sprite packing algorithms in SpriteAtlas V2. @@ -44,7 +45,7 @@ Custom packers are useful for: ### Abstract Methods -See [resources/scriptablepacker.cs](../resources/scriptablepacker.cs). +See [scripts/scriptablepacker.cs](../scripts/scriptablepacker.cs). ### PackerData Structure @@ -67,49 +68,49 @@ struct PackerData Information about each sprite: -See [resources/spritedata.cs](../resources/spritedata.cs). +See [scripts/spritedata.cs](../scripts/spritedata.cs). ### SpritePack Output Structure Set this on each `SpriteData` to specify packing result: -See [resources/spritepack.cs](../resources/spritepack.cs). +See [scripts/spritepack.cs](../scripts/spritepack.cs). ### TextureData Structure Source texture information: -See [resources/texturedata.cs](../resources/texturedata.cs). +See [scripts/texturedata.cs](../scripts/texturedata.cs). ### PackTransform Options Sprite transformations during packing: -See [resources/packtransform.cs](../resources/packtransform.cs). +See [scripts/packtransform.cs](../scripts/packtransform.cs). ## Example: Grid-Based Packer Simple example that arranges sprites in a grid pattern. -See [resources/gridspritepacker.cs](../resources/gridspritepacker.cs). +See [scripts/gridspritepacker.cs](../scripts/gridspritepacker.cs). ## Example: Multi-Page Packer Distributes sprites across multiple atlas pages. -See [resources/multipagepacker.cs](../resources/multipagepacker.cs). +See [scripts/multipagepacker.cs](../scripts/multipagepacker.cs). ## Example: Size-Optimized Packer Packs larger sprites first for better space utilization. -See [resources/sizeoptimizedpacker.cs](../resources/sizeoptimizedpacker.cs). +See [scripts/sizeoptimizedpacker.cs](../scripts/sizeoptimizedpacker.cs). ## Assigning Custom Packer to Atlas Use `SpriteAtlasAsset.SetScriptablePacker()` to assign your custom packer. -See [resources/custompackersetup.cs](../resources/custompackersetup.cs). +See [scripts/custompackersetup.cs](../scripts/custompackersetup.cs). ## Best Practices @@ -144,4 +145,4 @@ See [resources/custompackersetup.cs](../resources/custompackersetup.cs). ## Debugging Tips -See [resources/packerdebugging.cs](../resources/packerdebugging.cs). +See [scripts/packerdebugging.cs](../scripts/packerdebugging.cs). diff --git a/skills/using-unity/references/manage-sprite-atlas/references/docs-map.md b/skills/using-unity/references/manage-sprite-atlas/references/docs-map.md new file mode 100644 index 0000000..9e141a5 --- /dev/null +++ b/skills/using-unity/references/manage-sprite-atlas/references/docs-map.md @@ -0,0 +1,28 @@ +# Sprite atlas documentation pages + +Each Engine page lists its local file (under `<editor-install>/Editor/Data/Documentation/en/Manual/`, or `en/ScriptReference/` for Script Reference pages) and its online `.md` page. Replace `<VERSION>` with the project's Unity version (for example `6000.3`), or with the Addressables package major.minor for the Addressables pages. + +## Engine Manual and Script Reference + +- **Packing sprites into atlas textures** — local `sprite/atlas/atlas-landing.html`, online `https://docs.unity.com/en-us/engine/<VERSION>/manual/unity2d/sprite/atlas.md`: overview of sprite atlases, with links to every atlas page. + - **Create a sprite atlas** — local `sprite/atlas/create-sprite-atlas.html`, online `https://docs.unity.com/en-us/engine/<VERSION>/manual/unity2d/sprite/atlas/create-sprite-atlas.md`: what an atlas holds and how its packable objects are gathered. + - **Sprite Atlas Inspector window reference** — local `sprite/atlas/sprite-atlas-reference.html`, online `https://docs.unity.com/en-us/engine/<VERSION>/manual/unity2d/sprite/atlas/sprite-atlas-reference.md`: what each packing, texture and platform setting does. + - **Create lower resolution versions of sprite atlases** — local `sprite/atlas/master-variant/master-variant-sprite-atlases.html`, online `https://docs.unity.com/en-us/engine/<VERSION>/manual/unity2d/sprite/atlas/master-variant-sprite-atlases.md`: master and variant atlases, and how a variant scales the master's texture. + - **Load sprite atlases manually at runtime** — local `sprite/atlas/distribution/load-sprite-atlas-spriteatlasmanageratlasrequested.html`, online `https://docs.unity.com/en-us/engine/<VERSION>/manual/unity2d/sprite/atlas/load-sprite-atlas-spriteatlasmanageratlasrequested.md`: late binding with `SpriteAtlasManager.atlasRequested`. + - **Upgrade Sprite Atlas V1 assets** — local `sprite/atlas/v2/sprite-atlas-v2.html`, online `https://docs.unity.com/en-us/engine/<VERSION>/manual/unity2d/sprite/atlas/sprite-atlas-v2.md`: Sprite Atlas V2 and migrating from V1. +- **Choose a GPU texture format by platform** — local `texture-choose-format-by-platform.html`, online `https://docs.unity.com/en-us/engine/<VERSION>/manual/materials-and-shaders/textures/textures-getting-started/texture-compression-formats/texture-choose-format-by-platform.md`: which compression formats each platform supports, for platform overrides. +- **SpritePackerMode** (Script Reference) — local `SpritePackerMode.html`, online `https://docs.unity.com/en-us/engine/<VERSION>/script-reference/unityeditor/spritepackermode.md`: the values `EditorSettings.spritePackerMode` takes, including `Disabled`. +- **IPreprocessBuildWithReport** and **IPostprocessBuildWithReport** (Script Reference) — local `Build.IPreprocessBuildWithReport.html` and `Build.IPostprocessBuildWithReport.html`, online `https://docs.unity.com/en-us/engine/<VERSION>/script-reference/unityeditor/build/ipreprocessbuildwithreport.md` and `https://docs.unity.com/en-us/engine/<VERSION>/script-reference/unityeditor/build/ipostprocessbuildwithreport.md`: the build callbacks the generated scripts implement. + +## Addressables package + +Read these from `<project-folder>/Library/PackageCache/com.unity.addressables@*/`, or online under `https://docs.unity3d.com/Packages/com.unity.addressables@<VERSION>/manual/` if that folder has no .md files. + +- **Addressables package** — `Documentation~/index.md` (online `index.html`): overview of the package, with links to every page. + - **Addressables and sprite atlases** — `Documentation~/AddressablesAndSpriteAtlases.md` (online `AddressablesAndSpriteAtlases.html`): how atlases and their sprites load through Addressables. + - **Create a group** — `Documentation~/groups-create.md` (online `groups-create.html`): creating the group that holds the atlas entries. + - **Labels** — `Documentation~/Labels.md` (online `Labels.html`): tagging entries so atlases load by label. + - **Start a build from a script** — `Documentation~/build-scripting-start-build.md` (online `build-scripting-start-build.html`): building Addressables content from the postprocess script. + - **Build Addressables content with Player builds** — `Documentation~/build-player-builds.md` (online `build-player-builds.html`): building content as part of the player build. + - **Load assets** — `Documentation~/load-assets.md` (online `load-assets.html`): loading an atlas by address in the late-binding loader. + - **Release Addressable assets** — `Documentation~/UnloadingAddressableAssets.md` (online `UnloadingAddressableAssets.html`): releasing loaded atlases to free memory. diff --git a/skills/using-unity/references/manage-sprite-atlas/references/manual-authoring.md b/skills/using-unity/references/manage-sprite-atlas/references/manual-authoring.md index ecb705c..4d1c001 100644 --- a/skills/using-unity/references/manage-sprite-atlas/references/manual-authoring.md +++ b/skills/using-unity/references/manage-sprite-atlas/references/manual-authoring.md @@ -1,8 +1,9 @@ # Manual Authoring (Advanced - Not Default) +Relative paths in this file resolve to the skill directory — the folder that holds the skill's main instructions. > ⚠ **WARNING**: Manual authoring is NOT the default approach. Only use these patterns when the user EXPLICITLY requests manual control or editor preview during development. -> 🚨 **DEFAULT APPROACH**: Use prebuild generation with `IPreprocessBuildWithReport` instead. See the main SKILL.md Quick Start section. +> 🚨 **DEFAULT APPROACH**: Use prebuild generation with `IPreprocessBuildWithReport` instead. See the Procedure section of the parent skill. ## When to Use Manual Authoring @@ -22,18 +23,18 @@ > 🚨 **REMINDER**: Only use this if explicitly requested. Default is prebuild with `IPreprocessBuildWithReport`. -See [resources/createandconfiguremasteratlas.cs](../resources/createandconfiguremasteratlas.cs). +See [scripts/createandconfiguremasteratlas.cs](../scripts/createandconfiguremasteratlas.cs). ## Create Variant Atlas (Manual Pattern) > 🚨 **REMINDER**: Only use this if explicitly requested. Default is prebuild with `IPreprocessBuildWithReport`. -See [resources/variantatlas.cs](../resources/variantatlas.cs). +See [scripts/variantatlas.cs](../scripts/variantatlas.cs). ## Runtime Dynamic Loading -See [resources/runtimeatlasloader.cs](../resources/runtimeatlasloader.cs). +See [scripts/runtimeatlasloader.cs](../scripts/runtimeatlasloader.cs). ## Runtime Sprite Access -See [resources/runtimespriteaccess.cs](../resources/runtimespriteaccess.cs). +See [scripts/runtimespriteaccess.cs](../scripts/runtimespriteaccess.cs). diff --git a/skills/using-unity/references/manage-sprite-atlas/references/workflow.md b/skills/using-unity/references/manage-sprite-atlas/references/workflow.md new file mode 100644 index 0000000..e502428 --- /dev/null +++ b/skills/using-unity/references/manage-sprite-atlas/references/workflow.md @@ -0,0 +1,28 @@ +# Complete workflow + +``` +User Request + ↓ +Step 2: Check for existing scripts with [UNITY-SKILL:SPRITEATLAS] identifier + ↓ + ├─ Found existing scripts? + │ ↓ YES + │ Ask user: Update existing / Create new / Abort + │ ↓ + │ Handle user choice + │ + └─ NO existing scripts or user chose "Create new" + ↓ + Ask "Built-in data or Addressables?" + ↓ + ├─ Option A: Built-in + │ ↓ + │ Generate 1 script: Prebuild generator (includeInBuild=true) + │ + └─ Option B: Addressables + ↓ + Generate 3 scripts: + 1. Prebuild: Generate atlases + create Addressables entries (includeInBuild=false) + 2. Postprocess: Build Addressables bundles + 3. Runtime: Late-binding loader component +``` diff --git a/skills/using-unity/references/manage-sprite-atlas/resources/authoringvsruntime.cs b/skills/using-unity/references/manage-sprite-atlas/scripts/authoringvsruntime.cs similarity index 100% rename from skills/using-unity/references/manage-sprite-atlas/resources/authoringvsruntime.cs rename to skills/using-unity/references/manage-sprite-atlas/scripts/authoringvsruntime.cs diff --git a/skills/using-unity/references/manage-sprite-atlas/resources/buildaddressablespostprocess.cs b/skills/using-unity/references/manage-sprite-atlas/scripts/buildaddressablespostprocess.cs similarity index 100% rename from skills/using-unity/references/manage-sprite-atlas/resources/buildaddressablespostprocess.cs rename to skills/using-unity/references/manage-sprite-atlas/scripts/buildaddressablespostprocess.cs diff --git a/skills/using-unity/references/manage-sprite-atlas/resources/cacheloadedatlases.cs b/skills/using-unity/references/manage-sprite-atlas/scripts/cacheloadedatlases.cs similarity index 100% rename from skills/using-unity/references/manage-sprite-atlas/resources/cacheloadedatlases.cs rename to skills/using-unity/references/manage-sprite-atlas/scripts/cacheloadedatlases.cs diff --git a/skills/using-unity/references/manage-sprite-atlas/resources/cleanupbatchoperations.cs b/skills/using-unity/references/manage-sprite-atlas/scripts/cleanupbatchoperations.cs similarity index 100% rename from skills/using-unity/references/manage-sprite-atlas/resources/cleanupbatchoperations.cs rename to skills/using-unity/references/manage-sprite-atlas/scripts/cleanupbatchoperations.cs diff --git a/skills/using-unity/references/manage-sprite-atlas/resources/createandconfiguremasteratlas.cs b/skills/using-unity/references/manage-sprite-atlas/scripts/createandconfiguremasteratlas.cs similarity index 100% rename from skills/using-unity/references/manage-sprite-atlas/resources/createandconfiguremasteratlas.cs rename to skills/using-unity/references/manage-sprite-atlas/scripts/createandconfiguremasteratlas.cs diff --git a/skills/using-unity/references/manage-sprite-atlas/resources/custompackersetup.cs b/skills/using-unity/references/manage-sprite-atlas/scripts/custompackersetup.cs similarity index 100% rename from skills/using-unity/references/manage-sprite-atlas/resources/custompackersetup.cs rename to skills/using-unity/references/manage-sprite-atlas/scripts/custompackersetup.cs diff --git a/skills/using-unity/references/manage-sprite-atlas/resources/deprecatedmethods.cs b/skills/using-unity/references/manage-sprite-atlas/scripts/deprecatedmethods.cs similarity index 100% rename from skills/using-unity/references/manage-sprite-atlas/resources/deprecatedmethods.cs rename to skills/using-unity/references/manage-sprite-atlas/scripts/deprecatedmethods.cs diff --git a/skills/using-unity/references/manage-sprite-atlas/resources/dontmodifywithoutsaving.cs b/skills/using-unity/references/manage-sprite-atlas/scripts/dontmodifywithoutsaving.cs similarity index 100% rename from skills/using-unity/references/manage-sprite-atlas/resources/dontmodifywithoutsaving.cs rename to skills/using-unity/references/manage-sprite-atlas/scripts/dontmodifywithoutsaving.cs diff --git a/skills/using-unity/references/manage-sprite-atlas/resources/dontpackinruntimebuilds.cs b/skills/using-unity/references/manage-sprite-atlas/scripts/dontpackinruntimebuilds.cs similarity index 100% rename from skills/using-unity/references/manage-sprite-atlas/resources/dontpackinruntimebuilds.cs rename to skills/using-unity/references/manage-sprite-atlas/scripts/dontpackinruntimebuilds.cs diff --git a/skills/using-unity/references/manage-sprite-atlas/resources/dontscriptspriteatlasineditor.cs b/skills/using-unity/references/manage-sprite-atlas/scripts/dontscriptspriteatlasineditor.cs similarity index 100% rename from skills/using-unity/references/manage-sprite-atlas/resources/dontscriptspriteatlasineditor.cs rename to skills/using-unity/references/manage-sprite-atlas/scripts/dontscriptspriteatlasineditor.cs diff --git a/skills/using-unity/references/manage-sprite-atlas/resources/editorconfiguration.cs b/skills/using-unity/references/manage-sprite-atlas/scripts/editorconfiguration.cs similarity index 100% rename from skills/using-unity/references/manage-sprite-atlas/resources/editorconfiguration.cs rename to skills/using-unity/references/manage-sprite-atlas/scripts/editorconfiguration.cs diff --git a/skills/using-unity/references/manage-sprite-atlas/resources/enablespritepacking.cs b/skills/using-unity/references/manage-sprite-atlas/scripts/enablespritepacking.cs similarity index 100% rename from skills/using-unity/references/manage-sprite-atlas/resources/enablespritepacking.cs rename to skills/using-unity/references/manage-sprite-atlas/scripts/enablespritepacking.cs diff --git a/skills/using-unity/references/manage-sprite-atlas/resources/gridspritepacker.cs b/skills/using-unity/references/manage-sprite-atlas/scripts/gridspritepacker.cs similarity index 100% rename from skills/using-unity/references/manage-sprite-atlas/resources/gridspritepacker.cs rename to skills/using-unity/references/manage-sprite-atlas/scripts/gridspritepacker.cs diff --git a/skills/using-unity/references/manage-sprite-atlas/resources/handlelatebinding.cs b/skills/using-unity/references/manage-sprite-atlas/scripts/handlelatebinding.cs similarity index 100% rename from skills/using-unity/references/manage-sprite-atlas/resources/handlelatebinding.cs rename to skills/using-unity/references/manage-sprite-atlas/scripts/handlelatebinding.cs diff --git a/skills/using-unity/references/manage-sprite-atlas/resources/handlenullcases.cs b/skills/using-unity/references/manage-sprite-atlas/scripts/handlenullcases.cs similarity index 100% rename from skills/using-unity/references/manage-sprite-atlas/resources/handlenullcases.cs rename to skills/using-unity/references/manage-sprite-atlas/scripts/handlenullcases.cs diff --git a/skills/using-unity/references/manage-sprite-atlas/resources/migratev1tov2.cs b/skills/using-unity/references/manage-sprite-atlas/scripts/migratev1tov2.cs similarity index 100% rename from skills/using-unity/references/manage-sprite-atlas/resources/migratev1tov2.cs rename to skills/using-unity/references/manage-sprite-atlas/scripts/migratev1tov2.cs diff --git a/skills/using-unity/references/manage-sprite-atlas/resources/multipagepacker.cs b/skills/using-unity/references/manage-sprite-atlas/scripts/multipagepacker.cs similarity index 100% rename from skills/using-unity/references/manage-sprite-atlas/resources/multipagepacker.cs rename to skills/using-unity/references/manage-sprite-atlas/scripts/multipagepacker.cs diff --git a/skills/using-unity/references/manage-sprite-atlas/resources/optimizetexturesettings.cs b/skills/using-unity/references/manage-sprite-atlas/scripts/optimizetexturesettings.cs similarity index 100% rename from skills/using-unity/references/manage-sprite-atlas/resources/optimizetexturesettings.cs rename to skills/using-unity/references/manage-sprite-atlas/scripts/optimizetexturesettings.cs diff --git a/skills/using-unity/references/manage-sprite-atlas/resources/packerdebugging.cs b/skills/using-unity/references/manage-sprite-atlas/scripts/packerdebugging.cs similarity index 100% rename from skills/using-unity/references/manage-sprite-atlas/resources/packerdebugging.cs rename to skills/using-unity/references/manage-sprite-atlas/scripts/packerdebugging.cs diff --git a/skills/using-unity/references/manage-sprite-atlas/resources/packtransform.cs b/skills/using-unity/references/manage-sprite-atlas/scripts/packtransform.cs similarity index 100% rename from skills/using-unity/references/manage-sprite-atlas/resources/packtransform.cs rename to skills/using-unity/references/manage-sprite-atlas/scripts/packtransform.cs diff --git a/skills/using-unity/references/manage-sprite-atlas/resources/platformnames.cs b/skills/using-unity/references/manage-sprite-atlas/scripts/platformnames.cs similarity index 100% rename from skills/using-unity/references/manage-sprite-atlas/resources/platformnames.cs rename to skills/using-unity/references/manage-sprite-atlas/scripts/platformnames.cs diff --git a/skills/using-unity/references/manage-sprite-atlas/resources/queryspritesefficiently.cs b/skills/using-unity/references/manage-sprite-atlas/scripts/queryspritesefficiently.cs similarity index 100% rename from skills/using-unity/references/manage-sprite-atlas/resources/queryspritesefficiently.cs rename to skills/using-unity/references/manage-sprite-atlas/scripts/queryspritesefficiently.cs diff --git a/skills/using-unity/references/manage-sprite-atlas/resources/registercallbacks.cs b/skills/using-unity/references/manage-sprite-atlas/scripts/registercallbacks.cs similarity index 100% rename from skills/using-unity/references/manage-sprite-atlas/resources/registercallbacks.cs rename to skills/using-unity/references/manage-sprite-atlas/scripts/registercallbacks.cs diff --git a/skills/using-unity/references/manage-sprite-atlas/resources/runtimeatlasloader.cs b/skills/using-unity/references/manage-sprite-atlas/scripts/runtimeatlasloader.cs similarity index 100% rename from skills/using-unity/references/manage-sprite-atlas/resources/runtimeatlasloader.cs rename to skills/using-unity/references/manage-sprite-atlas/scripts/runtimeatlasloader.cs diff --git a/skills/using-unity/references/manage-sprite-atlas/resources/runtimespriteaccess.cs b/skills/using-unity/references/manage-sprite-atlas/scripts/runtimespriteaccess.cs similarity index 100% rename from skills/using-unity/references/manage-sprite-atlas/resources/runtimespriteaccess.cs rename to skills/using-unity/references/manage-sprite-atlas/scripts/runtimespriteaccess.cs diff --git a/skills/using-unity/references/manage-sprite-atlas/resources/savespriteatlasasset.cs b/skills/using-unity/references/manage-sprite-atlas/scripts/savespriteatlasasset.cs similarity index 100% rename from skills/using-unity/references/manage-sprite-atlas/resources/savespriteatlasasset.cs rename to skills/using-unity/references/manage-sprite-atlas/scripts/savespriteatlasasset.cs diff --git a/skills/using-unity/references/manage-sprite-atlas/resources/scriptablepacker.cs b/skills/using-unity/references/manage-sprite-atlas/scripts/scriptablepacker.cs similarity index 100% rename from skills/using-unity/references/manage-sprite-atlas/resources/scriptablepacker.cs rename to skills/using-unity/references/manage-sprite-atlas/scripts/scriptablepacker.cs diff --git a/skills/using-unity/references/manage-sprite-atlas/resources/setincludeinbuild.cs b/skills/using-unity/references/manage-sprite-atlas/scripts/setincludeinbuild.cs similarity index 100% rename from skills/using-unity/references/manage-sprite-atlas/resources/setincludeinbuild.cs rename to skills/using-unity/references/manage-sprite-atlas/scripts/setincludeinbuild.cs diff --git a/skills/using-unity/references/manage-sprite-atlas/resources/sizeoptimizedpacker.cs b/skills/using-unity/references/manage-sprite-atlas/scripts/sizeoptimizedpacker.cs similarity index 100% rename from skills/using-unity/references/manage-sprite-atlas/resources/sizeoptimizedpacker.cs rename to skills/using-unity/references/manage-sprite-atlas/scripts/sizeoptimizedpacker.cs diff --git a/skills/using-unity/references/manage-sprite-atlas/resources/spriteatlaslatebinding.cs b/skills/using-unity/references/manage-sprite-atlas/scripts/spriteatlaslatebinding.cs similarity index 100% rename from skills/using-unity/references/manage-sprite-atlas/resources/spriteatlaslatebinding.cs rename to skills/using-unity/references/manage-sprite-atlas/scripts/spriteatlaslatebinding.cs diff --git a/skills/using-unity/references/manage-sprite-atlas/resources/spriteatlasprebuildgenerator.cs b/skills/using-unity/references/manage-sprite-atlas/scripts/spriteatlasprebuildgenerator.cs similarity index 100% rename from skills/using-unity/references/manage-sprite-atlas/resources/spriteatlasprebuildgenerator.cs rename to skills/using-unity/references/manage-sprite-atlas/scripts/spriteatlasprebuildgenerator.cs diff --git a/skills/using-unity/references/manage-sprite-atlas/resources/spritedata.cs b/skills/using-unity/references/manage-sprite-atlas/scripts/spritedata.cs similarity index 100% rename from skills/using-unity/references/manage-sprite-atlas/resources/spritedata.cs rename to skills/using-unity/references/manage-sprite-atlas/scripts/spritedata.cs diff --git a/skills/using-unity/references/manage-sprite-atlas/resources/spritepack.cs b/skills/using-unity/references/manage-sprite-atlas/scripts/spritepack.cs similarity index 100% rename from skills/using-unity/references/manage-sprite-atlas/resources/spritepack.cs rename to skills/using-unity/references/manage-sprite-atlas/scripts/spritepack.cs diff --git a/skills/using-unity/references/manage-sprite-atlas/resources/texturedata.cs b/skills/using-unity/references/manage-sprite-atlas/scripts/texturedata.cs similarity index 100% rename from skills/using-unity/references/manage-sprite-atlas/resources/texturedata.cs rename to skills/using-unity/references/manage-sprite-atlas/scripts/texturedata.cs diff --git a/skills/using-unity/references/manage-sprite-atlas/resources/updatebuildscripts.cs b/skills/using-unity/references/manage-sprite-atlas/scripts/updatebuildscripts.cs similarity index 100% rename from skills/using-unity/references/manage-sprite-atlas/resources/updatebuildscripts.cs rename to skills/using-unity/references/manage-sprite-atlas/scripts/updatebuildscripts.cs diff --git a/skills/using-unity/references/manage-sprite-atlas/resources/updatesettingsconfiguration.cs b/skills/using-unity/references/manage-sprite-atlas/scripts/updatesettingsconfiguration.cs similarity index 100% rename from skills/using-unity/references/manage-sprite-atlas/resources/updatesettingsconfiguration.cs rename to skills/using-unity/references/manage-sprite-atlas/scripts/updatesettingsconfiguration.cs diff --git a/skills/using-unity/references/manage-sprite-atlas/resources/usevariantswisely.cs b/skills/using-unity/references/manage-sprite-atlas/scripts/usevariantswisely.cs similarity index 100% rename from skills/using-unity/references/manage-sprite-atlas/resources/usevariantswisely.cs rename to skills/using-unity/references/manage-sprite-atlas/scripts/usevariantswisely.cs diff --git a/skills/using-unity/references/manage-sprite-atlas/resources/variantatlas.cs b/skills/using-unity/references/manage-sprite-atlas/scripts/variantatlas.cs similarity index 100% rename from skills/using-unity/references/manage-sprite-atlas/resources/variantatlas.cs rename to skills/using-unity/references/manage-sprite-atlas/scripts/variantatlas.cs diff --git a/skills/using-unity/references/migrate-birp-to-urp/migrate-birp-to-urp.md b/skills/using-unity/references/migrate-birp-to-urp/migrate-birp-to-urp.md index 2345100..8be57b4 100644 --- a/skills/using-unity/references/migrate-birp-to-urp/migrate-birp-to-urp.md +++ b/skills/using-unity/references/migrate-birp-to-urp/migrate-birp-to-urp.md @@ -4,6 +4,52 @@ description: Plans, executes, and troubleshoots migration from the Built-in Rend --- Classify the request, inspect the current project state, choose the correct migration path, and validate the Built-in to URP migration outcome carefully. +## Important + +- Use the unity cli (`unity command --format json`) and the `unity-cli` and `unity-pipeline` skills for each step. +- Before making changes, establish a baseline of the current behavior so you can tell whether a later result is actually caused by your change. +- Create a restore point you can roll back to if your changes fail. +- Do only what's asked. Don't change unrelated assets or files. +- Never leave verification code in the user's script. Never build logging or detection they didn't ask for, because it clutters their project and console. Read state through `script eval` instead, as described in [Final step](#final-step). +- Avoid long explanations. + +## Full topic map + +Before you go forward with a workflow or diagnosis: + +1. Open and read the [documentation page(s)](#full-topic-map) that cover the specific subject related to what you intend to do or fix and check if you've missed anything. +2. Name the file(s) you read in your response. + +This is because your training knowledge about Unity might be out of date, incorrect, or for the wrong Unity version. + +If the Editor install folder has a `Data/Documentation` folder (eg `...Unity/Hub/Editor/6000.6.0b2/Editor/Data/Documentation`), read the html files from the `<editor-install>/Editor/Data/Documentation/en/Manual` folder. + +Otherwise the docs pages are online at `https://docs.unity.com/en-us/engine/<VERSION>/manual/`. + +Prefer `WebFetch` over `WebSearch` — faster and lands on the exact reference. Only fetch what you need. Replace `<VERSION>` with the following before fetching: + +- **Package on docs.unity3d.com**: The package version, eg `@6.6` or `@2.0`. Check the package version if unsure. +- **docs.unity.com**: The product version, eg `7000.0` + +Unity documentation: read [references/docs-map.md](references/docs-map.md) for the page list, with each page's local file name and online `.md` URL. + +### API reference + +The APIs are `UnityEngine.Rendering` and `UnityEditor` (Graphics and Quality settings, materials, lighting), part of the Unity Engine, and `UnityEngine.Rendering.Universal`, part of the `com.unity.render-pipelines.universal` package. The Engine API is versioned by Unity version and the URP API by package version, so check both before relying on a specific class or method. + +1. Use the `unity-cli` skill to check the project's Unity version and the installed URP package version. +2. For Engine APIs, if the Editor install folder has a `Data/Documentation` folder (e.g. `.../Unity/Hub/Editor/6000.6.0b2/Editor/Data/Documentation`), grep the html files in `<editor-install>/Editor/Data/Documentation/en/ScriptReference`, and skip to step 6. +3. Otherwise, fetch and cache `https://docs.unity3d.com/<VERSION>/Documentation/ScriptReference/xrefmap.yml` (replace `<VERSION>` with the Unity version, e.g. `6000.3`). This file lists every public API member's fully qualified name as a `uid` (e.g. `uid: 'UnityEngine.Rigidbody.AddForce(UnityEngine.Vector3)'`). +4. Grep the yml file locally for a class or method instead of refetching per lookup. The file is large (about 6 MB), so don't read the whole file. +5. Convert the `uid` to a markdown page: remove the parameters in brackets, lowercase it, replace `.` with `/`, and add `.md`. Then fetch `https://docs.unity.com/en-us/engine/<VERSION>/script-reference/<converted uid>`. For example, `UnityEngine.Rigidbody.AddForce(UnityEngine.Vector3)` => `https://docs.unity.com/en-us/engine/6000.3/script-reference/unityengine/rigidbody/addforce.md`. All overloads are on the same page. + - Constructors use `ctor` (e.g. `unityengine/vector3/ctor.md`), and indexers use `item` (e.g. `unityengine/vector3/item.md`). + - For operators, fetch the class page (e.g. `unityengine/vector3.md`) and follow its link. + - Links inside the pages start with `/engine/`. Add `https://docs.unity.com/en-us` before them. + - If the page doesn't exist for that Unity version, use the `href` in the `xrefmap.yml` entry instead (e.g. `href: 'Rigidbody.AddForce.html'` => `https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Rigidbody.AddForce.html`). +6. For URP APIs, fetch and cache `https://docs.unity3d.com/Packages/com.unity.render-pipelines.universal@<version>/xrefmap.yml` (replace `<version>` with the installed package version, e.g. `17.3`) and grep it locally. Each entry maps a fully qualified name to an `href` (e.g. `href: api/UnityEngine.Rendering.Universal.UniversalRenderPipelineAsset.html` => `https://docs.unity3d.com/Packages/com.unity.render-pipelines.universal@17.3/api/UnityEngine.Rendering.Universal.UniversalRenderPipelineAsset.html`). + +Always use the docs for the project's Unity and URP versions rather than relying on training knowledge, since APIs are frequently marked obsolete between versions. + ## Mandatory Execution Reference For any actual migration or repair pass, read [references/implementation-patterns.md](references/implementation-patterns.md) before the first `script eval` call that edits project settings, materials, post-processing, lighting, probes, or scenes. This is mandatory even for short prompts such as "migrate this project to URP" when rollback safety is already confirmed. @@ -38,50 +84,7 @@ One turn may complete multiple phases if the project is small and Unity remains Ask configuration questions only when the project state or user intent leaves a real decision unresolved. If the user says "do not modify files", stay in audit/planning mode and do not perform conversion or asset edits. -### Generic Upgrade Contract - -When the user gives a generic migration request and permits changes, drive the next phase from the project state: - -1. Do not ask the user to enumerate known Built-in features before inspection. Discover them. -2. If PPv2, baked lighting, reflection probes, particle/fog/smoke materials, or multiple Quality levels exist, include them in the migration automatically. -3. Prefer phase completion over all-in-one completion. Each phase should save/re-query its own outputs and end with `Phase complete`, `Phase partial`, or `Blocked`. -4. If Unity compilation, package installation, domain reload, or a long lighting bake interrupts the pass, report the interruption as a phase boundary and resume from saved partial state in the next turn rather than starting over. -5. Do not rely on the user writing a detailed checklist prompt to get correct behavior. The detailed checklist is for benchmarking or stress testing; normal user prompts should still trigger this phased contract. -6. A generic migration request gives permission to inspect and plan, but it does not prove rollback safety. If no rollback point is confirmed, stop before package install or URP assignment and ask for confirmation. Do not leave the project in a magenta partial state just to reach the backup question. -7. If rollback safety is already confirmed or the user says the project is a disposable copy, continue within the current phase without asking again for routine work. -8. At the end of a phase, give a concise next-phase prompt or say what phase should run next. Ask for confirmation before the next phase only when it introduces a new costly or risky operation, such as a long lighting bake, deletion/cleanup of legacy assets, or a custom shader rewrite. -9. If rollback safety was confirmed and ordinary work inside the active phase remains incomplete, do not ask "would you like me to continue?" Continue repairing that phase until its gate passes, a tool/domain-reload boundary interrupts execution, or a genuinely new risky decision appears. - -### Generic Migration Success Gate - -Before saying a generic migration is "successful", "complete", or "fully migrated", verify saved project state, not just tool logs: - -1. Graphics settings and every relevant Quality level point to the intended URP asset. -2. The URP asset has a valid default renderer in saved state, and current Console output does not contain unresolved render-pipeline errors such as "Default Renderer is missing". If a renderer error appears after assignment, re-query the saved renderer list/default index, clear stale Console output when possible, trigger a fresh scene/camera validation, and continue repair instead of stopping at "URP setup complete". -3. Supported Built-in materials, including particle/fog/smoke materials, have URP-compatible shaders or are explicitly listed as unresolved custom/package shader cases. Textured/colorized source materials must preserve their source maps/colors; a URP shader assignment with missing `_BaseMap` or all-white `_BaseColor` is incomplete if the source `_MainTex` or `_Color` had content. Particle, fog, smoke, steam, decal, VFX, additive, and transparent effect materials should not be blindly forced to `Universal Render Pipeline/Lit`; prefer URP particle/effect shaders such as `Universal Render Pipeline/Particles/Unlit` when appropriate. -4. If the source scene used PPv2, a saved URP `VolumeProfile` exists with persistent non-null override components, the representative scene references it through a URP `Volume`, and legacy PPv2 is disabled for URP visual validation. A saved profile with `components: []`, `{fileID: 0}` component refs, or a scene that still only references the old `PostProcessProfile` is incomplete. -5. If the representative scene uses baked/mixed lighting, an Enlighten/realtime-GI Lighting Settings asset, a Lighting Data asset, lightmaps, light probes, or reflection probes, do not leave routine lighting/probe repair as manual follow-up during a generic full migration. Attempt URP-compatible Lighting Settings assignment, clear/rebake or resume a bake when needed, refresh reflection probes when feasible, then save/reload and verify the scene references the intended lighting state. Creating a `.lighting` asset and calling `Lightmapping.lightingSettings = target` plus `AssetDatabase.SaveAssets()` is not enough; mark/save the scene, reload/re-query, and compare the saved scene `m_LightingSettings` reference or asset GUID. If a long bake or tool interruption prevents this, call the migration partial and resume from that phase. -6. A representative scene has been opened or selected deliberately before migration validation; do not infer baked-lighting or PPv2 absence from a default/test scene. The scene has been captured or inspected after saving/reloading, and Console output has been checked for render-pipeline, shader, or renderer-feature errors. -7. Final wording must match the gate result. Use "complete" only when every gate passes. Use "partial" when URP is set up but PPv2 Volume persistence, legacy PPv2 disablement, lighting bake/probe refresh, or saved-state validation remains. Do not start the final response with "successfully migrated" if any required gate is partial. - -Complete-report checklist: - -- If the old PPv2 profile contains active `DepthOfField`, the new URP profile must contain a saved `DepthOfField` override or the final report must call it omitted/manual. -- If the old PPv2 profile contains active `AmbientOcclusion`, configure a URP SSAO renderer feature when feasible, or mark AO as manual/partial. -- If the old PPv2 profile contains active `ScreenSpaceReflections`, list SSR as unsupported/manual unless a URP renderer-feature/custom replacement was actually added and validated. -- If the scene still serializes the old Lighting Settings GUID or a non-zero old `m_LightingDataAsset`, lighting is partial. -- If the scene has reflection probes and the URP asset still serializes `m_ReflectionProbeBlending: 0` or `m_ReflectionProbeBoxProjection: 0`, reflections are partial unless intentionally disabled and reported. -- If any checklist item is false, do not use "complete", "fully migrated", or "fully functional on URP" in the final answer. - -Unsupported features can remain manual, but name them precisely. Examples include PPv2 Screen Space Reflections needing a URP renderer-feature/custom/third-party replacement, complex custom shader ports, `GrabPass`, replacement shaders, or package-owned rendering code. If any success-gate item fails, continue repairing when allowed or report a partial migration with incomplete items; do not present the project as fully migrated. - -Regression guard summary: - -- Use the detailed [Execution Regression Checklist](references/implementation-patterns.md#execution-regression-checklist) for actual migration or repair work. -- Verify saved scene references before status claims: URP Volume/profile, Quality assignments, Lighting Settings/Data, URP asset/renderer, and reflection-probe settings. -- Preserve material source data from a pre-conversion snapshot, then restore `_BaseMap`, `_BaseColor`, texture scale/offsets, and relevant maps after shader changes. -- Validate representative visuals for PPv2, foliage, particles/effects, baked lighting, probes, and exposure before final wording. -- Report exact phase status. `Phase complete` is allowed for a passed phase; project-level `complete` is allowed only when every success gate passes. +Read [references/migration-gates.md](references/migration-gates.md) before any generic migration pass and before reporting status: it holds the generic upgrade contract and the success gate. ## Execution path: running C# in the Editor @@ -101,9 +104,12 @@ Two things it can't know for you: and `BuildCallbackContext`, which Unity introduced in **6000.3**; the package's own manifest declares `"unity": "6000.0"`, so it installs happily and then fails to compile. Measured: present in 6000.3 / 6000.4 / 6000.5, absent in 6000.0 / 6000.1 / 6000.2 and in the 2022 and 2023 - lines. The symptom is misleading — the server never starts, `unity status` shows no row and no - error, and the real cause is `CS0246` on those two types in the Editor log. If you see that, - tell the user the Editor is too old for the Pipeline package rather than debugging the CLI. + lines. The symptom is misleading — the server never starts and `unity status` shows no row and no + error: + + | Error | Cause | Fix | + |---|---|---| + | `CS0246` on `IPreprocessBuildWithContext` / `BuildCallbackContext` in the Editor log | Editor older than 6000.3 can't compile the Pipeline package. | Tell the user the Editor is too old for the Pipeline package; don't debug the CLI. | **This matters here more than in most skills:** someone migrating a project off the Built-in pipeline is, by definition, often on an older Editor. @@ -111,74 +117,17 @@ Two things it can't know for you: materials, and rebaking lighting all need a live Editor. An unreachable Editor is a stop, not a cue to hand-edit `ProjectSettings/GraphicsSettings.asset`. -Run C# with `unity command script eval --caller plugin --skill migrate-birp-to-urp --code '<snippet>'`. `unity command` defaults to a 30 second -timeout, which matters here: installing URP triggers a package refresh and domain reload that will -outlast it. Treat that as a phase boundary rather than raising the timeout. - -### Passing C# to `script eval` - -`script eval` compiles a **statement block, not a file**. Three consequences, all of which cause a compile -error rather than a warning: - -- **No `using` directives.** The compiler reads `using UnityEngine;` as a resource-disposal - statement and rejects it (`CS0210`). -- **Types must be fully qualified.** A bare `GraphicsSettings` or `Volume` does not resolve - (`CS0246` / `CS0103`), and a bare `Object` is ambiguous with `object` (`CS0104`). -- **Extension methods are unavailable**, because they resolve through `using`. Two that this skill - would otherwise reach for: `camera.GetUniversalAdditionalCameraData()` becomes - `camera.GetComponent<UnityEngine.Rendering.Universal.UniversalAdditionalCameraData>()`, and LINQ - calls must be written statically — `System.Linq.Enumerable.FirstOrDefault(sequence, predicate)` - rather than `sequence.FirstOrDefault(predicate)`. - -### Two execution modes — pick by the snippet's shape - -The references carry both shapes, and they are not interchangeable: - -- **Statement-shaped** (a bare sequence of statements, like the detection snippets above) — pass - straight to `script eval`, fully qualified, with no `using` lines. -- **Class- or method-shaped** (anything declaring a `class`, a `static` method, or a `[MenuItem]`, - such as the material-snapshot pattern) — these are **project files, not `script eval` input**. A class - declaration cannot be flattened into a statement block. Save the snippet under - `Assets/Editor/`, let Unity compile it, then invoke its entry point through a one-line `script eval` - call. Keep the `using` directives in that file; they are correct there. - -For a multi-step migration the script route is the more reliable one anyway: it survives the domain -reloads that URP installation and material conversion trigger, whereas a long `script eval` payload does -not. - -### Detecting the active render pipeline - -```csharp -var rp = UnityEngine.Rendering.GraphicsSettings.defaultRenderPipeline; -var qrp = UnityEngine.QualitySettings.renderPipeline; -return $"graphics={(rp == null ? "NULL (Built-in)" : rp.GetType().Name + ":" + rp.name)}, " - + $"activeQualityLevel={(qrp == null ? "inherits Graphics" : qrp.GetType().Name + ":" + qrp.name)}"; -``` - -A `UniversalRenderPipelineAsset` means URP; `HDRenderPipelineAsset` means HDRP; `NULL` on both -means Built-in. **Check the per-quality-level assignment too** — a project can be switched in -Graphics settings while a Quality level still points at a different asset, or at none: - -```csharp -var names = UnityEngine.QualitySettings.names; -var rows = new System.Collections.Generic.List<string>(); -for (int i = 0; i < names.Length; i++) -{ - var a = UnityEngine.QualitySettings.GetRenderPipelineAssetAt(i); - rows.Add($"{i}:{names[i]}={(a == null ? "inherits Graphics" : a.name)}"); -} -return string.Join(", ", rows); -``` - -If `GetRenderPipelineAssetAt` is unavailable in the project's Unity version, read -`ProjectSettings/QualitySettings.asset` instead rather than switching levels at runtime — -`SetQualityLevel` mutates project state. +Run C# with `unity command script eval --caller plugin --skill migrate-birp-to-urp --code '<snippet>'`. Its default timeout depends on the +Pipeline version, so read it from the command's schema (`unity command --detail full --format json`). +It matters here: installing URP triggers a package refresh and domain reload that will outlast it. Treat that as a phase boundary rather than raising the timeout. + +Read [references/eval-execution.md](references/eval-execution.md) before your first `script eval` call: it covers how to pass C# to `script eval`, the two execution modes, and the render-pipeline detection snippets. ## 0. Pre-Flight: Pipeline Detection and Reference Loading Before doing anything else, you **must determine the active render pipeline and migration mode**: -1. **Detect Pipeline:** Run the render-pipeline detection snippet from the execution-path section above. +1. **Detect Pipeline:** Run the render-pipeline detection snippet from [references/eval-execution.md](references/eval-execution.md). - If `currentRenderPipeline` or `defaultRenderPipelineAsset` references a `UniversalRenderPipelineAsset` -> **URP**. - If no render pipeline asset is assigned -> **Built-in**. - If it references an `HDRenderPipelineAsset` -> **HDRP**. Explain that this skill only covers Built-in to URP migration. Basic comparison advice is fine, but do not drive an HDRP migration with this skill. @@ -199,321 +148,52 @@ Before doing anything else, you **must determine the active render pipeline and ## 1. Assess Current Migration State -Before making any changes, **inspect what already exists**: - -1. **Inspect pipeline state and assignment points:** - - Run both render-pipeline detection snippets from the execution-path section above — the Graphics-settings one and the per-quality-level one. - - If the project has Quality levels, inspect which Render Pipeline Asset each level uses before assuming the project is fully switched. -2. **Inventory migration surfaces:** Use `script eval` with `UnityEditor.AssetDatabase.FindAssets` or equivalent asset queries to inventory: - - materials, including particle/VFX materials that often use built-in particle shaders - - vegetation materials, including grass, tree, terrain-detail, SpeedTree, billboard, leaf-card, cutout, and wind-driven foliage materials - - shaders - - scenes and important prefabs - - URP assets and renderer assets, if any - - post-processing profiles / volume profiles - - Lighting Settings assets, Lighting Data assets, lightmaps, light probes, reflection probes, and mixed/baked lights -3. **Scan for rendering risk markers:** Use available project-file search, `AssetDatabase.FindAssets`, or a short `script eval` file scan to search the project for rendering-specific patterns such as: - - `PostProcessLayer`, `PostProcessVolume`, `UnityEngine.Rendering.PostProcessing` - - `OnRenderImage(`, `RenderWithShader`, `SetReplacementShader` - - `#pragma surface`, `GrabPass`, `CGPROGRAM` - - `CommandBuffer`, custom shader include paths, or package shader namespaces - - vegetation markers such as `Nature/`, `SpeedTree`, `TreeCreator`, `Grass`, `Foliage`, `_Cutoff`, `_AlphaClip`, `_Cull`, billboard, or wind keywords -4. **If PPv2 is installed but grep finds nothing,** inspect open scenes and profile assets through Unity APIs by component/type. Scene YAML and serialized package references can be missed by text search. -5. **Determine project shape:** Decide whether the project is primarily 3D, primarily 2D, or mixed. -6. **Report Findings:** Summarize the current state before proposing conversion. Example: - - "The project is still on Built-in, has no URP asset assigned, contains PPv2 references, and includes several custom shaders using surface-shader syntax." +Read [references/assess-migration-state.md](references/assess-migration-state.md) before making any changes: it covers inspecting pipeline state, inventorying migration surfaces, scanning for rendering risk markers, and reporting findings. ## 2. Gather Requirements -Determine what the user actually wants. If the request is ambiguous, ask. - -Use these defaults for common requests: - -| User says | Default interpretation | -|-----------|------------------------| -| "Upgrade this project to URP" | Full-project migration | -| "Move this 2D project to URP" | Built-in 2D to URP 2D migration | -| "Convert these materials" | Targeted material conversion | -| "My materials turned pink" | Post-migration shader/material troubleshooting | -| "Lighting looks wrong after URP" | Quality and visual parity troubleshooting | -| "Do not change anything yet" | Planning / audit only | - -### Information to Gather - -- **Scope:** full project, selected materials, or troubleshooting only -- **Target renderer:** standard URP or URP 2D -- **Validation targets:** which scenes, prefabs, or cameras matter most to the user -- **Risk tolerance:** whether limited manual follow-up is acceptable -- **Rendering dependencies:** custom shaders, Asset Store shaders, PPv2, baked lighting/lightmaps/probes, image effects, command buffers, replacement shaders, or multiple Quality levels -- **Execution permission:** planning only vs actual project changes +Read [references/gather-requirements.md](references/gather-requirements.md) to interpret the request and find out scope, target renderer, validation targets, and execution permission. ## 3. Safety Gate Before any pipeline-mutating step: 1. **Confirm rollback safety.** - - NEVER install URP, assign a URP asset, run the Render Pipeline Converter, edit materials, or edit migration scene state before the user confirms a backup, branch, archive, disposable copy, or rollback point. - - If rollback safety is missing, do not partially switch the project to URP. Stop in planning mode and ask for the rollback confirmation first. + - NEVER install URP, assign a URP asset, run the Render Pipeline Converter, edit materials, or edit migration scene state before the user confirms a backup, branch, archive, disposable copy, or rollback point, because assigning a URP asset immediately turns Built-in materials magenta and the converter has no undo. + - If rollback safety is missing, do not partially switch the project to URP, because a half-switched project renders neither pipeline correctly. Stop in planning mode and ask for the rollback confirmation first. 2. **Separate engine-upgrade risk from pipeline-upgrade risk.** - - If the project is also moving to a new Unity version, recommend doing the engine upgrade first and the pipeline migration second. Do not treat both as a single blind operation. + - If the project is also moving to a new Unity version, recommend doing the engine upgrade first and the pipeline migration second. Do not treat both as a single blind operation, because mixing the two hides which change broke what. 3. **If rollback safety is confirmed,** treat it as covering the whole migration pass. Do not ask again before each converter; proceed through setup, material conversion, PPv2 migration, lighting/probe work, save/reload verification, and final reporting unless a new risky decision appears. 4. **If the user already authorized a full disposable migration,** do not ask for permission to continue after routine setup or recoverable errors. Continue with the next incomplete migration phase. Ask only when a new destructive cleanup decision appears, a package/domain reload stops execution, or repeated repair attempts hit the validation iteration limit. -4. **If the project is already partially migrated,** identify whether rollback safety was previously confirmed. If yes, resume from the first incomplete item. If no, report the partial state and ask before making additional changes. - -## 4. Choose the Migration Path - -Use the correct path for the project: - -### Path A: Standard 3D Built-in to URP -- Use this for normal 3D Built-in projects moving to standard URP. - -### Path B: Built-in 2D to URP 2D -- Use this when the project is primarily 2D and the user expects URP 2D lighting or renderer behavior. -- Do not treat this as the same workflow as standard URP. - -### Path C: Targeted Material-Only Conversion -- Use this only when the project is already on URP and the user wants selected materials converted. - -### Path D: Troubleshooting an Existing Migration -- Use this when the project is already on URP or the migration has already been attempted. -- Prioritize the highest-impact breakages instead of re-running the entire migration blindly. - -## 5. URP Setup Workflow - -Follow this exact setup order: - -1. **Ensure URP is installed.** - - Installing URP can trigger package refresh, compilation, and domain reload. Treat this as a phase boundary. - - Do not spin-wait indefinitely inside an `script eval` call on `UnityEditor.PackageManager.Client.Add`. Request installation, then verify through `Packages/manifest.json`, package listing, or the presence of URP types/assets after Unity finishes refreshing. - - If the package install causes the `script eval` call to time out or return nothing, resume in a fresh turn after Unity finishes compiling. Do not restart the whole migration or reinstall URP; inspect the partial state and continue from there. -2. **Create the required URP asset and renderer asset** if they do not already exist. -3. **Assign the URP asset in Graphics settings** and in all relevant Quality levels. -4. **For 2D projects,** create and assign the correct 2D Renderer asset before conversion. -5. **If a URP asset already exists,** inspect and reuse it when appropriate instead of creating duplicates automatically. -6. **Do not continue** until URP is actually the active render pipeline for the target configuration. - -## 6. Conversion Workflow - -For actual conversion work, follow [references/migration-workflow.md](references/migration-workflow.md). - -1. **Choose the correct Render Pipeline Converter path:** - - `Built-in Render Pipeline to URP` - - `Built-in Render Pipeline 2D to URP 2D` -2. **Initialize converters and inspect the candidate changes** before converting. -3. **For standard Built-in to URP migration,** prefer the applicable converters described in the reference: - - `Rendering Settings` - - `Material Upgrade` - - `Animation Clip Converter` - - `Read-only Material Converter` - - `Post-processing Stack v2 Converter` -4. **For selected-material conversion,** use the targeted material conversion workflow instead of converting the whole project. -5. **Review warnings and failures before converting.** -6. **Run the conversion only after the user confirms the project is safe to change.** -7. **Verify which shader each material actually landed on** — do not assume the converter chose the 3D - target. `MaterialUpgrader.FetchAllUpgradersForPipeline` returns the 2D provider set alongside the 3D - one, and both claim `Standard` at equal priority, so on a 3D project a plain `Standard` material can - silently convert to `Universal Render Pipeline/2D/Mesh2D-Lit-Default` instead of - `Universal Render Pipeline/Lit`. Nothing errors and the material does not go magenta, so this is - invisible unless you read the shader name back — measured on 6000.5.8f1. - - Read every converted material's `shader.name` afterwards and confirm it matches the intended target - from the mapping table. If any landed on a `2D/` shader in a 3D project, restore those materials from - the rollback point and convert them with a 3D-filtered upgrader list, or with the manual pattern in - [references/implementation-patterns.md](references/implementation-patterns.md). -7. **After conversion, verify the saved project state.** - - Re-open or re-query representative assets instead of trusting command output alone. - - Save both assets and open scenes after scene-level edits. Changes to scene components, camera data, active lighting settings, reflection probes, and PPv2 enable states are not proven by `AssetDatabase.SaveAssets()` alone. - - Confirm the URP asset is assigned in Graphics and intended Quality levels. - - For Quality levels, validate by re-querying `QualitySettings.GetRenderPipelineAssetAt(i)` or by reading the saved `customRenderPipeline` entries in `ProjectSettings/QualitySettings.asset`. If they remain `{fileID: 0}`, the Quality levels are not explicitly assigned. - - Do not call a guessed quality API such as `QualitySettings.SetRenderPipelineAssetAt`; in Unity versions where that API is unavailable, switch to each target level with `QualitySettings.SetQualityLevel(index)`, set `QualitySettings.renderPipeline = urpAsset`, then restore the original level and verify the saved `customRenderPipeline` values. - - Confirm converted materials actually reference URP shaders. - - Confirm representative materials that had source albedo textures now have non-null `_BaseMap` values. This check must compare against a pre-conversion material snapshot; do not use post-conversion `_MainTex` as the source of truth. - - Confirm particle/VFX materials no longer reference Built-in particle shader IDs or legacy shader names; use URP particle shaders such as `Universal Render Pipeline/Particles/Unlit` where appropriate. If material names or paths include `Particle`, `Fog`, `Smoke`, `Steam`, `VFX`, `Additive`, or similar effect terms, preserve transparent/additive behavior rather than defaulting them to URP Lit. - - Confirm vegetation materials preserve cutout/alpha clipping, render face intent, textures, tint, normals, and expected wind/billboard behavior. If grass/tree cards become solid or static because their specialized shader behavior was lost, material conversion is partial. - - If PPv2 conversion was attempted, confirm saved URP Volume profiles contain persistent non-null `components` entries and the scene/camera wiring uses URP-compatible components. - - If baked lighting exists, preserve the old Lighting Data and lightmaps as reference data, then verify whether they still produce acceptable URP visuals. If a new Lighting Settings asset is created, verify the saved scene actually references it after saving/reloading; the asset existing on disk is not enough. In an actual generic migration, attempt rebaking/refreshing when stale baked data or reflection probes affect parity; if that cannot finish in the current turn, report the migration as partial and resume from the lighting/probe phase later. - - Do not claim "refreshed reflection probes" from intent. Verify new or updated probe outputs, changed saved reflection-probe assets, or successful probe-render tool output. If the existing EXR files remain unchanged, say probes were preserved as reference or still need refresh. - - If any verification fails, report the item as incomplete/manual follow-up, not as migrated. - -## 7. Shader and Material Triage - -When materials are magenta, shaders fail to compile, or visuals drift heavily, use [references/custom-shader-triage.md](references/custom-shader-triage.md) first. - -1. **Identify affected materials and shaders.** - - Inspect the exact material shader assignments, not just scene symptoms. -2. **Read Console and Inspector errors before editing shader code.** -3. **Classify the shader case:** - - supported Built-in shaders that the converter should handle - - simple custom shaders that might be ported safely - - complex custom shaders that need a scoped migration plan - - foliage/vegetation shaders that require cutout, two-sided leaves, billboards, terrain detail rendering, or wind behavior - - package-owned or Asset Store shaders that may require maintainer documentation, scoped custom porting, or manual follow-up -4. **For complex shader situations,** use [references/complex-shader-situations.md](references/complex-shader-situations.md). -5. **Prefer the smallest safe fix.** - - Restore rendering on representative materials first. - - Validate the result before scaling the fix to more assets. -6. **Never bulk search-and-replace shader code across the whole project** unless the mapping is explicit, tested, and scoped. - -## 8. Post-Processing, Cameras, and Rendering-Effect Triage - -Built-in projects often rely on more than material conversion. - -1. **If PPv2 is present,** inspect the converter output and validate the resulting URP volumes, profiles, and camera behavior. - - Inventory existing `PostProcessVolume`, `PostProcessLayer`, and PPv2 `PostProcessProfile` assets before conversion. - - Prefer the URP `Post-processing Stack v2 Converter` when available instead of hand-building equivalent profiles from memory. - - After conversion, verify that saved URP `VolumeProfile` assets contain persistent override components, not an empty `components: []` profile or dangling `{fileID: 0}` component references. - - If creating a profile by script, `VolumeProfile.Add<T>()` only creates a component object; for persistent profile assets, also call `AssetDatabase.AddObjectToAsset(component, profile)`, mark the profile and component dirty, save assets, reload the asset, and count saved non-null components before reporting success. If the saved profile has `{fileID: 0}` component entries, recreate or repair the profile before claiming migration success. - - Verify representative scenes contain the intended `Volume` objects and that target cameras have `UniversalAdditionalCameraData` with post-processing enabled when required. - - If the source scene still only serializes a PPv2 `sharedProfile` reference and no URP `Volume` references the new `VolumeProfile`, PPv2 migration is incomplete even if a URP profile asset exists on disk. - - If an active URP `Volume` references an empty profile, treat that as incomplete scene wiring, not as active post-processing. Repair the profile or report PPv2 as partial. - - Check whether old `PostProcessVolume` / `PostProcessLayer` components remain. If they remain, explain whether they are intentionally retained, harmless legacy leftovers, or unresolved migration work. - - If old PPv2 components are retained only as reference while a URP Volume is active, disable the old PPv2 component/layer for URP visual validation to avoid double post-processing. Do not delete it until parity is accepted or the user approves cleanup. - - Do not remove PPv2 packages, components, or profiles as a cleanup step until a verified URP replacement exists or the user accepts that those effects will be dropped/manual follow-up. - - During an actual migration, do not leave common PPv2 parity as a vague manual task if the source profile is available. Create persistent URP overrides for common mappable effects such as Bloom, Color Adjustments/Tonemapping, Vignette, and Depth of Field, then verify the saved profile has non-null components. - - It is acceptable to mark unsupported or non-equivalent effects as manual follow-up, such as PPv2 Screen Space Reflections or Ambient Occlusion that should become a renderer feature / SSAO setup instead of a direct Volume override. - - If URP Volume overrides cannot be created reliably, document the PPv2 effects and their URP equivalents instead of claiming they were migrated. -2. **Do not treat transient tool success as post-processing success.** - - A command log that says "Added Bloom" is not enough. Re-read the saved `VolumeProfile` asset or inspect the scene after saving/reloading. - - If the saved profile is empty, say the PPv2 setup was documented or partially prepared, not migrated. -3. **If grep finds `OnRenderImage`,** treat it as a custom full-screen effect case. - - In URP, custom full-screen effects should move toward `ScriptableRenderPass`, a Renderer Feature, or URP custom post-processing instead of staying on the Built-in image-effect path. -4. **If grep finds `RenderWithShader` or `SetReplacementShader`,** treat it as a replacement-shader case. - - These effects often need a deliberate URP renderer-feature or custom-pass strategy. -5. **If an effect depends on scene color, depth, or normals,** verify the URP-compatible path rather than assuming the Built-in approach still applies. -6. **If custom cameras were stacking effects in Built-in,** validate camera output explicitly after migration instead of assuming parity. -7. **For advanced shader/effect troubleshooting questions, provide concrete replacement patterns.** - - For `GrabPass`, mention `_CameraOpaqueTexture` / Scene Color, the required URP asset setting, and the limitation that transparent ordering can differ from Built-in. - - For `OnRenderImage`, mention `ScriptableRendererFeature` plus `ScriptableRenderPass`. When showing a Unity 6-style template, use the reference pattern with a temporary `RTHandle` and `Blitter.BlitCameraTexture`. - - Never recommend `Blitter.BlitCameraTexture(cmd, source, source, material, pass)` or other source-to-source blits as the main `OnRenderImage` replacement. If you are not going to show the safer temporary-target pattern, omit the code sample and explain the architecture instead. - - For Surface Shaders, state that `#pragma surface` has no direct URP equivalent and choose Shader Graph or a URP HLSL vertex/fragment rewrite based on effect complexity. - - Do not stop at "rewrite it"; give the user a practical first porting step and a validation target. - -## 9. Quality, Lighting, and Visual Parity Review - -Use [references/quality-settings-map.md](references/quality-settings-map.md) when the user mentions visual mismatch, shadows, performance, or quality settings. - -1. **Review Graphics settings and each active Quality level.** - - If a Quality level has no custom URP asset, state whether that level intentionally falls back to Graphics settings or still needs explicit assignment. - - Do not claim all quality levels are migrated unless each relevant level has been inspected. - - If using serialized project settings, the saved field is commonly `customRenderPipeline`; writing a guessed field such as `renderPipelineAsset` is not enough unless the saved asset proves the assignment. - - If assigning through script, use the same pattern as URP's Render Settings converter: cache `QualitySettings.GetQualityLevel()`, call `QualitySettings.SetQualityLevel(index)` for each target level, assign `QualitySettings.renderPipeline = urpAsset`, then restore the original quality level and verify on disk. -2. **Check URP asset settings** that commonly affect parity: - - shadows - - shadow distance and cascades - - MSAA - - render scale - - HDR, opaque texture, and depth texture settings when effects depend on them -3. **Do not promise identical lighting automatically.** - - Built-in and URP can differ in light falloff, baked GI appearance, shadow tuning, reflection probe response, tonemapping, exposure, and post-processing behavior. -4. **For baked lighting scenes,** treat existing lightmaps and Lighting Data as reference material, not guaranteed-final URP output. - - Inventory `Lightmapping.lightingSettings`, scene `LightmapSettings`, baked/mixed lights, light probes, reflection probes, and any existing `LightingDataAsset`. - - Preserve baked data until the user has a visual reference or rollback point, but do not keep stale Built-in lightmaps active as the final URP lighting solution if they blow out or distort the scene. - - If the scene looks blown out, too dark, or mismatched, first isolate post-processing/exposure by disabling legacy PPv2 during URP validation, then review URP Volume exposure/tonemapping/bloom before changing lights. - - If clearing baked data makes the scene stop being blown out, identify the old lightmaps/Lighting Data as stale or incompatible active data. Then rebake under URP with the final URP asset, renderer, Volume, and Quality settings instead of tuning lights against the stale bake. - - If creating or assigning URP-compatible `LightingSettings`, mark the lighting settings and active scene dirty, save the scene, reload or re-query, and verify the saved scene references the intended `.lighting` asset. `AssetDatabase.SaveAssets()` alone does not save the scene's `Lightmapping.lightingSettings` reference. Do not report "Baked GI enabled" if the saved scene still points at an Enlighten/realtime-GI settings asset. - - When visual parity is part of the request and old `LightingData.asset` / reflection-probe EXRs remain from the Built-in bake, treat them as reference data until rebaked/refreshed under URP. Do not claim visual parity is preserved from old bake data alone. - - Recommend clearing/rebaking lighting and refreshing reflection probes when visual parity matters. Do not claim baked lighting was successfully migrated unless a representative scene has been visually checked after URP setup, and preferably after a URP bake. -5. **For 2D lighting projects,** ensure sprites and tilemaps use URP-compatible lit materials where required. -6. **For performance regressions,** inspect whether the issue is coming from: - - heavier URP asset settings - - post-processing - - extra shadow cost - - custom shader ports or non-batched shaders -7. **When changing URP asset settings,** re-read the saved asset or query the property after saving before reporting values such as MSAA, additional-light limits, HDR, depth texture, or opaque texture. - -## 10. Validation - -After setup, conversion, or troubleshooting, validate the result: - -1. **Capture the scene:** Capture the Scene View or a specific camera on a representative scene — see [references/capturing-the-editor.md](references/capturing-the-editor.md). -2. **Evaluate the result:** - - no magenta materials unless unresolved custom shader blockers remain - - main lighting and shadows behave as expected - - baked GI/lightmaps, light probes, and reflection probes are acceptable or explicitly marked for rebake/refresh - - cameras render expected content - - post-processing or fullscreen effects still behave correctly - - sprites, tilemaps, or 2D lights work when relevant -3. **Verify persistent project data, not only visual output.** - - Inspect saved URP assets, renderer assets, scene references, material shader GUIDs/names, Quality settings, and Volume profiles. - - Confirm the representative scene, not a default/test scene, was opened or otherwise inspected before concluding that baked lighting, PPv2, or reflection probes are absent. - - For material migration, include particle/VFX materials in the verification. Remaining built-in particle shader IDs or legacy particle shader names mean material migration is incomplete. - - For PPv2 migrations, saved URP `VolumeProfile` assets must contain the expected override components before reporting them as migrated. - - If a tool log reports mapped post-processing but the saved profile reloads with `components: []`, override the tool log and report the migration as failed/incomplete. - - For baked-lighting scenes, inspect Lighting Settings, Lighting Data/lightmap references, light probes, and reflection probes. Compilation success does not prove baked lighting parity. If old lightmaps cause overexposure, clear active baked data and rebake under URP before judging parity. After assigning new lighting settings, verify the saved scene reference, not only the existence of the new `.lighting` asset. - - If old `LightingData.asset` remains assigned and reflection-probe EXRs were not regenerated or explicitly accepted after visual inspection, classify lighting/probes as preserved or partial rather than refreshed. -4. **Check Console output** with `Unity.GetConsoleLogs` for shader, render pipeline, or renderer-feature errors. -5. **Fix the highest-impact issue first,** then validate again. -6. **Repeat for at most 3 iterations** before reporting remaining blockers or asking the user how they want to proceed. - -## 11. Troubleshooting Decision Tree - -If the user reports a migration problem, follow this diagnostic flow: - -### Project still behaves like Built-in after "migration" -1. Check whether a URP asset is assigned in Graphics settings. -2. Check whether the relevant Quality levels also point to a URP asset. -3. Verify that the active render pipeline is actually URP before troubleshooting anything else. - -### Migration stopped after installing URP -1. Treat this as a package-refresh/domain-reload boundary, not a failed full migration by itself. -2. Re-check `Packages/manifest.json` and package state. If URP is installed, do not reinstall it. -3. Inspect for partial assets such as URP assets, renderer assets, converted materials, empty Volume profiles, and scene component changes. -4. If URP is installed/assigned but Built-in materials still dominate or the scene is magenta, material conversion is the immediate next incomplete item. Do not call URP setup complete and stop there if rollback safety has already been confirmed. -5. Continue from the first incomplete verification item: Graphics/Quality assignment, renderer asset validity, material conversion, PPv2-to-URP Volume migration, baked-lighting rebake, then final validation. -6. If the previous chat/export has no final response, report it as incomplete evidence and continue in a fresh chat/turn. - -### Materials are magenta / bright pink -1. Check Console and Inspector for shader errors. -2. Confirm whether the material uses a supported Built-in shader, a custom shader, or a package-owned shader. -3. If it is a supported Built-in shader, review the converter path or targeted material conversion first. -4. If the project is already on URP and many supported Built-in materials remain, treat this as incomplete material conversion, not as final visual parity work. -5. If it is a custom or package shader, move into [references/custom-shader-triage.md](references/custom-shader-triage.md) and, when needed, [references/complex-shader-situations.md](references/complex-shader-situations.md). - -### Scene is much darker, brighter, or just "wrong" -1. Compare Scene View and Game View captures. -2. Check for double post-processing first: retained PPv2 `PostProcessVolume` / `PostProcessLayer` plus an active URP `Volume` can overexpose or otherwise distort validation captures. -3. Review shadows, ambient/environment lighting, tone mapping, skybox, exposure, bloom, and post-processing. -4. Inspect baked lighting state: Lighting Settings, Lighting Data asset, lightmap references, mixed/baked lights, light probes, and reflection probes. -5. Review quality-level assignments and URP asset settings before rewriting content. -6. If clearing baked data fixes severe overexposure, treat the old lightmaps as stale active data: keep them only as reference/rollback evidence, then rebake under URP. -7. If the scene depends on baked lighting, recommend a URP rebake and reflection-probe refresh before claiming visual parity. -8. Remember that Built-in and URP light falloff can differ; treat that as a tuning task, not proof that conversion failed. - -### Post-processing or fullscreen effects disappeared -1. Check whether PPv2 was converted and whether the target camera and volume setup are still valid. -2. Inspect saved URP `VolumeProfile` assets. Empty profiles mean PPv2 effects were not actually migrated. -3. Check whether old `PostProcessVolume` / `PostProcessLayer` components remain active in scenes. -4. Search for `OnRenderImage`, custom blit code, or replacement-shader camera effects. -5. Port the effect using a URP-compatible approach rather than trying to preserve the Built-in callback path unchanged. - -### Transparent / refraction / distortion effects broke -1. Inspect whether the shader relied on `GrabPass` or a similar Built-in screen-copy workflow. -2. If so, use [references/complex-shader-situations.md](references/complex-shader-situations.md) and choose a Scene Color / Renderer Feature / custom-pass approach. - -### 2D lights are not affecting sprites -1. Confirm the project is actually using the 2D Renderer. -2. Confirm existing sprite materials were upgraded to URP-compatible lit materials where needed. -3. Do not assume dragged-in new sprites prove old project materials are correct. - -### Performance regressed after migration -1. Review render scale, shadows, additional lights, MSAA, post-processing, opaque/depth textures, and other URP asset settings. -2. Check whether custom shader ports lost batching compatibility or introduced extra passes. -3. Tune settings before assuming the only answer is a rollback. - -### Custom shader compiles but visuals are still wrong -1. Determine whether the issue is simple parameter drift or a structural incompatibility. -2. If the shader came from a surface shader, `GrabPass`, replacement-shader workflow, or custom lighting path, treat it as a complex migration case. -3. Validate one representative material before rolling the approach out project-wide. +5. **If the project is already partially migrated,** identify whether rollback safety was previously confirmed. If yes, resume from the first incomplete item. If no, report the partial state and ask before making additional changes. + +## 4-8. Migration Path, URP Setup, Conversion, and Triage + +Read [references/setup-and-conversion.md](references/setup-and-conversion.md) before choosing the migration path, setting up URP, converting materials, or triaging shaders, post-processing, and camera effects. + +## 9-11. Parity, Validation, and Troubleshooting + +Read [references/parity-validation-troubleshooting.md](references/parity-validation-troubleshooting.md) after setup, conversion, or troubleshooting, and when the user reports visual mismatch, lighting, performance, or other post-migration problems. ## 12. Core Guardrails -- Detect the active render pipeline first; for HDRP, explain the mismatch and offer only basic comparison guidance. -- Do not mutate the project before rollback safety is confirmed; instead stop in planning mode before URP install, asset assignment, converters, material edits, or scene edits. -- Do not treat tool logs or created assets as proof; instead save/reload/re-query Graphics, Quality, materials, Volumes, lighting, probes, Console, and representative scenes before status claims. -- Do not collapse partial phases into project-level completion; instead report `Phase complete`, `Partial migration`, and `Manual follow-up` based on the success gate. -- Do not bulk-rewrite fragile rendering code; instead use scoped mappings for custom shaders, `GrabPass`, `OnRenderImage`, replacement shaders, package-owned render code, and unsupported PPv2 effects. +- Detect the active render pipeline first; for HDRP, explain the mismatch and offer only basic comparison guidance, because this skill covers Built-in to URP only. +- Do not mutate the project before rollback safety is confirmed; instead stop in planning mode before URP install, asset assignment, converters, material edits, or scene edits, because converter changes are one-way. +- Do not treat tool logs or created assets as proof; instead save/reload/re-query Graphics, Quality, materials, Volumes, lighting, probes, Console, and representative scenes before status claims, because many of these changes look applied in logs but don't persist. +- Do not collapse partial phases into project-level completion; instead report `Phase complete`, `Partial migration`, and `Manual follow-up` based on the success gate, because an over-claimed "complete" hides work the user still has to do. +- Do not bulk-rewrite fragile rendering code; instead use scoped mappings for custom shaders, `GrabPass`, `OnRenderImage`, replacement shaders, package-owned render code, and unsupported PPv2 effects, because these have no automatic converter path and blind rewrites break them silently. + +## 13. Final step + +Do the following checks: -## 13. Reporting Back +1. Check the project has zero console errors. Use `console status` for counts. +2. For a migration or repair pass, don't stop at console counts: pass the success gate in [references/migration-gates.md](references/migration-gates.md), including the representative-scene capture in [references/capturing-the-editor.md](references/capturing-the-editor.md). For planning-only or audit requests, stop after step 1. +3. If the change affects runtime behaviour and you do enter Play mode, do it once only to chase a fault you already suspect. Read the world through `script eval` rather than adding logging. + +If a check fails, go back and reread the [docs pages](#full-topic-map) to find out what you missed. + +## 14. Reporting Back Summarize: @@ -531,13 +211,3 @@ Summarize: - whether exposure, tonemapping, ambient fill, and camera/Volume post-processing wiring were visually balanced or still remain partial Use completion language conservatively. If the report contains any `Partial`, `Manual follow-up`, `not validated`, `may still need`, or unsupported-feature item, state that specific completed phases passed and call the overall migration partial/manual. Do not pair a project-level "complete" claim with manual follow-up bullets. - -## References - -- [Migration Workflow](references/migration-workflow.md) -- [Custom Shader Triage](references/custom-shader-triage.md) -- [Complex Shader Situations](references/complex-shader-situations.md) -- [Quality Settings Map](references/quality-settings-map.md) -- [Implementation Patterns](references/implementation-patterns.md) - -When this skill is activated, proactively read [references/migration-workflow.md](references/migration-workflow.md). If the request involves materials, shaders, magenta materials, custom rendering, or fullscreen effects, also read [references/custom-shader-triage.md](references/custom-shader-triage.md) and [references/complex-shader-situations.md](references/complex-shader-situations.md). If the request involves visual mismatch, lighting, baked lighting, lightmaps, reflection probes, shadows, or performance after migration, also read [references/quality-settings-map.md](references/quality-settings-map.md). If the user permits actual migration changes or asks to continue/repair a partial migration, also read [references/implementation-patterns.md](references/implementation-patterns.md). diff --git a/skills/using-unity/references/migrate-birp-to-urp/references/assess-migration-state.md b/skills/using-unity/references/migrate-birp-to-urp/references/assess-migration-state.md new file mode 100644 index 0000000..f2e4fb0 --- /dev/null +++ b/skills/using-unity/references/migrate-birp-to-urp/references/assess-migration-state.md @@ -0,0 +1,31 @@ +# Assess Current Migration State + +How to inspect what already exists before proposing conversion. + +Links to other reference files point to files in this `references/` folder. Any other relative paths resolve to the skill directory. + +## 1. Assess Current Migration State + +Before making any changes, **inspect what already exists**: + +1. **Inspect pipeline state and assignment points:** + - Run both render-pipeline detection snippets from [references/eval-execution.md](eval-execution.md) — the Graphics-settings one and the per-quality-level one. + - If the project has Quality levels, inspect which Render Pipeline Asset each level uses before assuming the project is fully switched. +2. **Inventory migration surfaces:** Use `script eval` with `UnityEditor.AssetDatabase.FindAssets` or equivalent asset queries to inventory: + - materials, including particle/VFX materials that often use built-in particle shaders + - vegetation materials, including grass, tree, terrain-detail, SpeedTree, billboard, leaf-card, cutout, and wind-driven foliage materials + - shaders + - scenes and important prefabs + - URP assets and renderer assets, if any + - post-processing profiles / volume profiles + - Lighting Settings assets, Lighting Data assets, lightmaps, light probes, reflection probes, and mixed/baked lights +3. **Scan for rendering risk markers:** Use available project-file search, `AssetDatabase.FindAssets`, or a short `script eval` file scan to search the project for rendering-specific patterns such as: + - `PostProcessLayer`, `PostProcessVolume`, `UnityEngine.Rendering.PostProcessing` + - `OnRenderImage(`, `RenderWithShader`, `SetReplacementShader` + - `#pragma surface`, `GrabPass`, `CGPROGRAM` + - `CommandBuffer`, custom shader include paths, or package shader namespaces + - vegetation markers such as `Nature/`, `SpeedTree`, `TreeCreator`, `Grass`, `Foliage`, `_Cutoff`, `_AlphaClip`, `_Cull`, billboard, or wind keywords +4. **If PPv2 is installed but grep finds nothing,** inspect open scenes and profile assets through Unity APIs by component/type. Scene YAML and serialized package references can be missed by text search. +5. **Determine project shape:** Decide whether the project is primarily 3D, primarily 2D, or mixed. +6. **Report Findings:** Summarize the current state before proposing conversion. Example: + - "The project is still on Built-in, has no URP asset assigned, contains PPv2 references, and includes several custom shaders using surface-shader syntax." diff --git a/skills/using-unity/references/migrate-birp-to-urp/references/complex-shader-situations.md b/skills/using-unity/references/migrate-birp-to-urp/references/complex-shader-situations.md index b5b0ecf..981d8fe 100644 --- a/skills/using-unity/references/migrate-birp-to-urp/references/complex-shader-situations.md +++ b/skills/using-unity/references/migrate-birp-to-urp/references/complex-shader-situations.md @@ -16,11 +16,13 @@ Use deliberate URP migration strategies for higher-risk Built-in rendering patte ## Official References -- [Render pipeline feature comparison](https://docs.unity3d.com/Manual/render-pipelines-feature-comparison.html) -- [Upgrade custom shaders for URP compatibility](https://docs.unity3d.com/Manual/urp/urp-shaders/birp-urp-custom-shader-upgrade-guide.html) -- [Camera.OnRenderImage](https://docs.unity3d.com/ScriptReference/Camera.OnRenderImage.html) -- [Custom post-processing in URP](https://docs.unity3d.com/Manual/urp/post-processing/custom-post-processing.html) -- [Make a shader compatible with the Deferred rendering path in URP](https://docs.unity3d.com/Manual/urp/rendering/make-shader-compatible-with-deferred.html) +Read each page's local copy from `<editor-install>/Editor/Data/Documentation/en/Manual/<local file>` (or `en/ScriptReference/` for API pages) when it exists, otherwise the online `.md` page. Replace `<VERSION>` with the project's Unity version, e.g. `6000.3`. + +- [Render pipeline feature comparison](https://docs.unity.com/en-us/engine/<VERSION>/manual/render-pipelines/choose-a-render-pipeline/feature-comparison.md) — local `render-pipelines-feature-comparison.html` +- [Upgrade custom shaders for URP compatibility](https://docs.unity.com/en-us/engine/<VERSION>/manual/render-pipelines/universal-render-pipeline/introduction/installing-and-configuring-urp/upgrading-from-birp/upgrade-shaders/birp-urp-custom-shader-upgrade-guide.md) — local `urp/urp-shaders/birp-urp-custom-shader-upgrade-guide.html` +- [Camera.OnRenderImage](https://docs.unity.com/en-us/engine/<VERSION>/script-reference/unityengine/camera/onrenderimage.md) — local `Camera.OnRenderImage.html` +- [Custom post-processing in URP](https://docs.unity.com/en-us/engine/<VERSION>/manual/post-processing-and-full-screen-effects/urp/custom-post-processing.md) — local `urp/post-processing/custom-post-processing.html` +- [Make a shader compatible with the Deferred rendering path in URP](https://docs.unity.com/en-us/engine/<VERSION>/manual/render-pipelines/universal-render-pipeline/introduction/urp-concepts/rendering-paths/deferred-rendering-path/make-shader-compatible-with-deferred.md) — local `urp/rendering/make-shader-compatible-with-deferred.html` ## Ground Truth diff --git a/skills/using-unity/references/migrate-birp-to-urp/references/custom-shader-triage.md b/skills/using-unity/references/migrate-birp-to-urp/references/custom-shader-triage.md index cfe6258..f66d55d 100644 --- a/skills/using-unity/references/migrate-birp-to-urp/references/custom-shader-triage.md +++ b/skills/using-unity/references/migrate-birp-to-urp/references/custom-shader-triage.md @@ -2,6 +2,8 @@ Use this triage for shader and material cases that the Render Pipeline Converter cannot solve automatically. +Links to other reference files point to files in this `references/` folder. Any other relative paths resolve to the skill directory. + ## Table of Contents - [Official Reference](#official-reference) @@ -15,9 +17,11 @@ Use this triage for shader and material cases that the Render Pipeline Converter ## Official Reference -- [Upgrade custom shaders for URP compatibility](https://docs.unity3d.com/Manual/urp/urp-shaders/birp-urp-custom-shader-upgrade-guide.html) -- [Upgrade material assets to URP or HDRP](https://docs.unity3d.com/Manual/upgrade-material.html) -- [Render pipeline feature comparison](https://docs.unity3d.com/Manual/render-pipelines-feature-comparison.html) +Read each page's local copy from `<editor-install>/Editor/Data/Documentation/en/Manual/<local file>` (or `en/ScriptReference/` for API pages) when it exists, otherwise the online `.md` page. Replace `<VERSION>` with the project's Unity version, e.g. `6000.3`. + +- [Upgrade custom shaders for URP compatibility](https://docs.unity.com/en-us/engine/<VERSION>/manual/render-pipelines/universal-render-pipeline/introduction/installing-and-configuring-urp/upgrading-from-birp/upgrade-shaders/birp-urp-custom-shader-upgrade-guide.md) — local `urp/urp-shaders/birp-urp-custom-shader-upgrade-guide.html` +- [Upgrade material assets to URP or HDRP](https://docs.unity.com/en-us/engine/<VERSION>/manual/materials-and-shaders/materials/upgrade-material.md) — local `upgrade-material.html` +- [Render pipeline feature comparison](https://docs.unity.com/en-us/engine/<VERSION>/manual/render-pipelines/choose-a-render-pipeline/feature-comparison.md) — local `render-pipelines-feature-comparison.html` ## Ground Truth diff --git a/skills/using-unity/references/migrate-birp-to-urp/references/docs-map.md b/skills/using-unity/references/migrate-birp-to-urp/references/docs-map.md new file mode 100644 index 0000000..210e8ca --- /dev/null +++ b/skills/using-unity/references/migrate-birp-to-urp/references/docs-map.md @@ -0,0 +1,18 @@ +# Docs map + +Unity Manual pages for the Built-in to URP migration. Each entry gives the online `.md` page and the local file name. + +Read each page's local copy from `<editor-install>/Editor/Data/Documentation/en/Manual/<local file>` (or `en/ScriptReference/` for API pages) when it exists, otherwise the online `.md` page. Replace `<VERSION>` with the project's Unity version, e.g. `6000.3`. + +If a page isn't found, fetch https://docs.unity.com/en-us/engine/<VERSION>/manual.md and search it for the page title. + +- [Upgrading from the Built-in Render Pipeline to URP](https://docs.unity.com/en-us/engine/<VERSION>/manual/render-pipelines/universal-render-pipeline/introduction/installing-and-configuring-urp/upgrading-from-birp.md) — local `urp/upgrading-from-birp.html`: the overall upgrade order (install URP, assign assets, convert). +- [Install URP into an existing project](https://docs.unity.com/en-us/engine/<VERSION>/manual/render-pipelines/universal-render-pipeline/introduction/installing-and-configuring-urp/creating-a-urp-project/install-urpinto-aproject.md) — local `urp/InstallURPIntoAProject.html`: creating the URP asset and assigning it in Graphics and Quality settings. +- [Convert assets using the Render Pipeline Converter](https://docs.unity.com/en-us/engine/<VERSION>/manual/render-pipelines/universal-render-pipeline/introduction/installing-and-configuring-urp/upgrading-from-birp/rp-converter.md) — local `urp/features/rp-converter.html`: how to open the converter, the conversion types, and what each converter does. +- [Upgrade material assets to URP or HDRP](https://docs.unity.com/en-us/engine/<VERSION>/manual/materials-and-shaders/materials/upgrade-material.md) — local `upgrade-material.html`: converting selected materials and the Built-in to URP shader mappings. +- [Upgrade custom shaders for URP compatibility](https://docs.unity.com/en-us/engine/<VERSION>/manual/render-pipelines/universal-render-pipeline/introduction/installing-and-configuring-urp/upgrading-from-birp/upgrade-shaders/birp-urp-custom-shader-upgrade-guide.md) — local `urp/urp-shaders/birp-urp-custom-shader-upgrade-guide.html`: hand-porting Built-in shaders. +- [Prepare and upgrade sprites for 2D lighting in URP](https://docs.unity.com/en-us/engine/<VERSION>/manual/unity2d/2d-urp/2d-index/prep-shader.md) — local `urp/PrepShader.html`: sprite materials that react to 2D lights. +- [Find Built-in quality settings in URP](https://docs.unity.com/en-us/engine/<VERSION>/manual/render-pipelines/universal-render-pipeline/introduction/installing-and-configuring-urp/upgrading-from-birp/quality-settings-location.md) — local `urp/birp-onboarding/quality-settings-location.html`: where each Built-in quality setting lives in URP. +- [Volumes](https://docs.unity.com/en-us/engine/<VERSION>/manual/post-processing-and-full-screen-effects/urp/volumes-landing-page/volumes.md) — local `urp/Volumes.html`: URP Volume and Volume Profile setup that replaces PPv2. +- [Reflection probes in URP](https://docs.unity.com/en-us/engine/<VERSION>/manual/lighting-overview/lighting/reflection-probes.md) — local `urp/lighting/reflection-probes.html`: how reflection probes work in URP. +- [Render pipeline feature comparison](https://docs.unity.com/en-us/engine/<VERSION>/manual/render-pipelines/choose-a-render-pipeline/feature-comparison.md) — local `render-pipelines-feature-comparison.html`: Built-in features that URP lacks or handles differently. diff --git a/skills/using-unity/references/migrate-birp-to-urp/references/eval-execution.md b/skills/using-unity/references/migrate-birp-to-urp/references/eval-execution.md new file mode 100644 index 0000000..691c164 --- /dev/null +++ b/skills/using-unity/references/migrate-birp-to-urp/references/eval-execution.md @@ -0,0 +1,60 @@ +# Running C# with `script eval` + +### Passing C# to `script eval` + +`script eval` compiles a **statement block, not a file**. Three consequences, all of which cause a compile +error rather than a warning: + +- **No `using` directives.** The compiler reads `using UnityEngine;` as a resource-disposal + statement and rejects it (`CS0210`). +- **Types must be fully qualified.** A bare `GraphicsSettings` or `Volume` does not resolve + (`CS0246` / `CS0103`), and a bare `Object` is ambiguous with `object` (`CS0104`). +- **Extension methods are unavailable**, because they resolve through `using`. Two that this skill + would otherwise reach for: `camera.GetUniversalAdditionalCameraData()` becomes + `camera.GetComponent<UnityEngine.Rendering.Universal.UniversalAdditionalCameraData>()`, and LINQ + calls must be written statically — `System.Linq.Enumerable.FirstOrDefault(sequence, predicate)` + rather than `sequence.FirstOrDefault(predicate)`. + +### Two execution modes — pick by the snippet's shape + +The references carry both shapes, and they are not interchangeable: + +- **Statement-shaped** (a bare sequence of statements, like the detection snippets above) — pass + straight to `script eval`, fully qualified, with no `using` lines. +- **Class- or method-shaped** (anything declaring a `class`, a `static` method, or a `[MenuItem]`, + such as the material-snapshot pattern) — these are **project files, not `script eval` input**. A class + declaration cannot be flattened into a statement block. Save the snippet under + `Assets/Editor/`, let Unity compile it, then invoke its entry point through a one-line `script eval` + call. Keep the `using` directives in that file; they are correct there. + +For a multi-step migration the script route is the more reliable one anyway: it survives the domain +reloads that URP installation and material conversion trigger, whereas a long `script eval` payload does +not. + +### Detecting the active render pipeline + +```csharp +var rp = UnityEngine.Rendering.GraphicsSettings.defaultRenderPipeline; +var qrp = UnityEngine.QualitySettings.renderPipeline; +return $"graphics={(rp == null ? "NULL (Built-in)" : rp.GetType().Name + ":" + rp.name)}, " + + $"activeQualityLevel={(qrp == null ? "inherits Graphics" : qrp.GetType().Name + ":" + qrp.name)}"; +``` + +A `UniversalRenderPipelineAsset` means URP; `HDRenderPipelineAsset` means HDRP; `NULL` on both +means Built-in. **Check the per-quality-level assignment too** — a project can be switched in +Graphics settings while a Quality level still points at a different asset, or at none: + +```csharp +var names = UnityEngine.QualitySettings.names; +var rows = new System.Collections.Generic.List<string>(); +for (int i = 0; i < names.Length; i++) +{ + var a = UnityEngine.QualitySettings.GetRenderPipelineAssetAt(i); + rows.Add($"{i}:{names[i]}={(a == null ? "inherits Graphics" : a.name)}"); +} +return string.Join(", ", rows); +``` + +If `GetRenderPipelineAssetAt` is unavailable in the project's Unity version, read +`ProjectSettings/QualitySettings.asset` instead rather than switching levels at runtime — +`SetQualityLevel` mutates project state. diff --git a/skills/using-unity/references/migrate-birp-to-urp/references/gather-requirements.md b/skills/using-unity/references/migrate-birp-to-urp/references/gather-requirements.md new file mode 100644 index 0000000..0a0c053 --- /dev/null +++ b/skills/using-unity/references/migrate-birp-to-urp/references/gather-requirements.md @@ -0,0 +1,29 @@ +# Gather Requirements + +How to interpret common requests and what to find out before migrating. + +Links to other reference files point to files in this `references/` folder. Any other relative paths resolve to the skill directory. + +## 2. Gather Requirements + +Determine what the user actually wants. If the request is ambiguous, ask. + +Use these defaults for common requests: + +| User says | Default interpretation | +|-----------|------------------------| +| "Upgrade this project to URP" | Full-project migration | +| "Move this 2D project to URP" | Built-in 2D to URP 2D migration | +| "Convert these materials" | Targeted material conversion | +| "My materials turned pink" | Post-migration shader/material troubleshooting | +| "Lighting looks wrong after URP" | Quality and visual parity troubleshooting | +| "Do not change anything yet" | Planning / audit only | + +### Information to Gather + +- **Scope:** full project, selected materials, or troubleshooting only +- **Target renderer:** standard URP or URP 2D +- **Validation targets:** which scenes, prefabs, or cameras matter most to the user +- **Risk tolerance:** whether limited manual follow-up is acceptable +- **Rendering dependencies:** custom shaders, Asset Store shaders, PPv2, baked lighting/lightmaps/probes, image effects, command buffers, replacement shaders, or multiple Quality levels +- **Execution permission:** planning only vs actual project changes diff --git a/skills/using-unity/references/migrate-birp-to-urp/references/implementation-patterns.md b/skills/using-unity/references/migrate-birp-to-urp/references/implementation-patterns.md index 0a0d9e2..d030473 100644 --- a/skills/using-unity/references/migrate-birp-to-urp/references/implementation-patterns.md +++ b/skills/using-unity/references/migrate-birp-to-urp/references/implementation-patterns.md @@ -453,7 +453,7 @@ var camera = System.Linq.Enumerable.FirstOrDefault(cameras, c => c.name == "Main ?? UnityEngine.Camera.main; if (camera != null) { - // GetUniversalAdditionalCameraData() is an extension method and needs a `using`, which eval + // GetUniversalAdditionalCameraData() is an extension method and needs a `using`, which script eval // rejects — read the component it wraps instead. var data = camera.GetComponent<UnityEngine.Rendering.Universal.UniversalAdditionalCameraData>(); report.Add(data != null diff --git a/skills/using-unity/references/migrate-birp-to-urp/references/migration-gates.md b/skills/using-unity/references/migrate-birp-to-urp/references/migration-gates.md new file mode 100644 index 0000000..5776f7a --- /dev/null +++ b/skills/using-unity/references/migrate-birp-to-urp/references/migration-gates.md @@ -0,0 +1,50 @@ +# Migration Gates + +The phase contract for generic migration requests and the success gate to pass before calling a migration complete. + +Links to other reference files point to files in this `references/` folder. Any other relative paths resolve to the skill directory. + +### Generic Upgrade Contract + +When the user gives a generic migration request and permits changes, drive the next phase from the project state: + +1. Do not ask the user to enumerate known Built-in features before inspection. Discover them. +2. If PPv2, baked lighting, reflection probes, particle/fog/smoke materials, or multiple Quality levels exist, include them in the migration automatically. +3. Prefer phase completion over all-in-one completion. Each phase should save/re-query its own outputs and end with `Phase complete`, `Phase partial`, or `Blocked`. +4. If Unity compilation, package installation, domain reload, or a long lighting bake interrupts the pass, report the interruption as a phase boundary and resume from saved partial state in the next turn rather than starting over. +5. Do not rely on the user writing a detailed checklist prompt to get correct behavior. The detailed checklist is for benchmarking or stress testing; normal user prompts should still trigger this phased contract. +6. A generic migration request gives permission to inspect and plan, but it does not prove rollback safety. If no rollback point is confirmed, stop before package install or URP assignment and ask for confirmation. Do not leave the project in a magenta partial state just to reach the backup question. +7. If rollback safety is already confirmed or the user says the project is a disposable copy, continue within the current phase without asking again for routine work. +8. At the end of a phase, give a concise next-phase prompt or say what phase should run next. Ask for confirmation before the next phase only when it introduces a new costly or risky operation, such as a long lighting bake, deletion/cleanup of legacy assets, or a custom shader rewrite. +9. If rollback safety was confirmed and ordinary work inside the active phase remains incomplete, do not ask "would you like me to continue?" Continue repairing that phase until its gate passes, a tool/domain-reload boundary interrupts execution, or a genuinely new risky decision appears. + +### Generic Migration Success Gate + +Before saying a generic migration is "successful", "complete", or "fully migrated", verify saved project state, not just tool logs: + +1. Graphics settings and every relevant Quality level point to the intended URP asset. +2. The URP asset has a valid default renderer in saved state, and current Console output does not contain unresolved render-pipeline errors such as "Default Renderer is missing". If a renderer error appears after assignment, re-query the saved renderer list/default index, clear stale Console output when possible, trigger a fresh scene/camera validation, and continue repair instead of stopping at "URP setup complete". +3. Supported Built-in materials, including particle/fog/smoke materials, have URP-compatible shaders or are explicitly listed as unresolved custom/package shader cases. Textured/colorized source materials must preserve their source maps/colors; a URP shader assignment with missing `_BaseMap` or all-white `_BaseColor` is incomplete if the source `_MainTex` or `_Color` had content. Particle, fog, smoke, steam, decal, VFX, additive, and transparent effect materials should not be blindly forced to `Universal Render Pipeline/Lit`; prefer URP particle/effect shaders such as `Universal Render Pipeline/Particles/Unlit` when appropriate. +4. If the source scene used PPv2, a saved URP `VolumeProfile` exists with persistent non-null override components, the representative scene references it through a URP `Volume`, and legacy PPv2 is disabled for URP visual validation. A saved profile with `components: []`, `{fileID: 0}` component refs, or a scene that still only references the old `PostProcessProfile` is incomplete. +5. If the representative scene uses baked/mixed lighting, an Enlighten/realtime-GI Lighting Settings asset, a Lighting Data asset, lightmaps, light probes, or reflection probes, do not leave routine lighting/probe repair as manual follow-up during a generic full migration. Attempt URP-compatible Lighting Settings assignment, clear/rebake or resume a bake when needed, refresh reflection probes when feasible, then save/reload and verify the scene references the intended lighting state. Creating a `.lighting` asset and calling `Lightmapping.lightingSettings = target` plus `AssetDatabase.SaveAssets()` is not enough; mark/save the scene, reload/re-query, and compare the saved scene `m_LightingSettings` reference or asset GUID. If a long bake or tool interruption prevents this, call the migration partial and resume from that phase. +6. A representative scene has been opened or selected deliberately before migration validation; do not infer baked-lighting or PPv2 absence from a default/test scene. The scene has been captured or inspected after saving/reloading, and Console output has been checked for render-pipeline, shader, or renderer-feature errors. +7. Final wording must match the gate result. Use "complete" only when every gate passes. Use "partial" when URP is set up but PPv2 Volume persistence, legacy PPv2 disablement, lighting bake/probe refresh, or saved-state validation remains. Do not start the final response with "successfully migrated" if any required gate is partial. + +Complete-report checklist: + +- If the old PPv2 profile contains active `DepthOfField`, the new URP profile must contain a saved `DepthOfField` override or the final report must call it omitted/manual. +- If the old PPv2 profile contains active `AmbientOcclusion`, configure a URP SSAO renderer feature when feasible, or mark AO as manual/partial. +- If the old PPv2 profile contains active `ScreenSpaceReflections`, list SSR as unsupported/manual unless a URP renderer-feature/custom replacement was actually added and validated. +- If the scene still serializes the old Lighting Settings GUID or a non-zero old `m_LightingDataAsset`, lighting is partial. +- If the scene has reflection probes and the URP asset still serializes `m_ReflectionProbeBlending: 0` or `m_ReflectionProbeBoxProjection: 0`, reflections are partial unless intentionally disabled and reported. +- If any checklist item is false, do not use "complete", "fully migrated", or "fully functional on URP" in the final answer. + +Unsupported features can remain manual, but name them precisely. Examples include PPv2 Screen Space Reflections needing a URP renderer-feature/custom/third-party replacement, complex custom shader ports, `GrabPass`, replacement shaders, or package-owned rendering code. If any success-gate item fails, continue repairing when allowed or report a partial migration with incomplete items; do not present the project as fully migrated. + +Regression guard summary: + +- Use the detailed [Execution Regression Checklist](implementation-patterns.md#execution-regression-checklist) for actual migration or repair work. +- Verify saved scene references before status claims: URP Volume/profile, Quality assignments, Lighting Settings/Data, URP asset/renderer, and reflection-probe settings. +- Preserve material source data from a pre-conversion snapshot, then restore `_BaseMap`, `_BaseColor`, texture scale/offsets, and relevant maps after shader changes. +- Validate representative visuals for PPv2, foliage, particles/effects, baked lighting, probes, and exposure before final wording. +- Report exact phase status. `Phase complete` is allowed for a passed phase; project-level `complete` is allowed only when every success gate passes. diff --git a/skills/using-unity/references/migrate-birp-to-urp/references/migration-workflow.md b/skills/using-unity/references/migrate-birp-to-urp/references/migration-workflow.md index 1e00697..e579e12 100644 --- a/skills/using-unity/references/migrate-birp-to-urp/references/migration-workflow.md +++ b/skills/using-unity/references/migrate-birp-to-urp/references/migration-workflow.md @@ -19,13 +19,15 @@ Use this workflow to follow the official Unity migration flow and identify when ## Official References -- [Upgrading from the Built-in Render Pipeline to URP](https://docs.unity3d.com/Manual/urp/upgrading-from-birp.html) -- [Convert assets using the Render Pipeline Converter](https://docs.unity3d.com/Manual/urp/features/rp-converter.html) -- [Upgrade material assets to URP or HDRP](https://docs.unity3d.com/Manual/upgrade-material.html) -- [URP asset](https://docs.unity3d.com/Manual/urp/urp-asset-and-renderer.html) -- [Prepare and upgrade sprites for 2D lighting in URP](https://docs.unity3d.com/Manual/urp/PrepShader.html) -- [Set up a render pipeline](https://docs.unity3d.com/Manual/render-pipelines-set-up.html) -- [Update believable visuals in URP and HDRP](https://docs.unity3d.com/Manual/BestPracticeMakingBelievableVisuals0.html) +Read each page's local copy from `<editor-install>/Editor/Data/Documentation/en/Manual/<local file>` (or `en/ScriptReference/` for API pages) when it exists, otherwise the online `.md` page. Replace `<VERSION>` with the project's Unity version, e.g. `6000.3`. + +- [Upgrading from the Built-in Render Pipeline to URP](https://docs.unity.com/en-us/engine/<VERSION>/manual/render-pipelines/universal-render-pipeline/introduction/installing-and-configuring-urp/upgrading-from-birp.md) — local `urp/upgrading-from-birp.html` +- [Convert assets using the Render Pipeline Converter](https://docs.unity.com/en-us/engine/<VERSION>/manual/render-pipelines/universal-render-pipeline/introduction/installing-and-configuring-urp/upgrading-from-birp/rp-converter.md) — local `urp/features/rp-converter.html` +- [Upgrade material assets to URP or HDRP](https://docs.unity.com/en-us/engine/<VERSION>/manual/materials-and-shaders/materials/upgrade-material.md) — local `upgrade-material.html` +- [URP asset](https://docs.unity.com/en-us/engine/<VERSION>/manual/render-pipelines/universal-render-pipeline/urp-quality-settings/urp-asset-and-renderer.md) — local `urp/urp-asset-and-renderer.html` +- [Prepare and upgrade sprites for 2D lighting in URP](https://docs.unity.com/en-us/engine/<VERSION>/manual/unity2d/2d-urp/2d-index/prep-shader.md) — local `urp/PrepShader.html` +- [Set up a render pipeline](https://docs.unity.com/en-us/engine/<VERSION>/manual/render-pipelines/choose-a-render-pipeline/set-up.md) — local `render-pipelines-set-up.html` +- [Update believable visuals in URP and HDRP](https://docs.unity3d.com/<VERSION>/Documentation/Manual/BestPracticeMakingBelievableVisuals0.html) ## Safety First diff --git a/skills/using-unity/references/migrate-birp-to-urp/references/parity-validation-troubleshooting.md b/skills/using-unity/references/migrate-birp-to-urp/references/parity-validation-troubleshooting.md new file mode 100644 index 0000000..3706cf0 --- /dev/null +++ b/skills/using-unity/references/migrate-birp-to-urp/references/parity-validation-troubleshooting.md @@ -0,0 +1,128 @@ +# Parity, Validation, and Troubleshooting + +Quality and lighting parity review, validation after each pass, and the troubleshooting decision tree. + +Links to other reference files point to files in this `references/` folder. Any other relative paths resolve to the skill directory. + +## Contents + +- 9. Quality, Lighting, and Visual Parity Review +- 10. Validation +- 11. Troubleshooting Decision Tree + +## 9. Quality, Lighting, and Visual Parity Review + +Use [quality-settings-map.md](quality-settings-map.md) when the user mentions visual mismatch, shadows, performance, or quality settings. + +1. **Review Graphics settings and each active Quality level.** + - If a Quality level has no custom URP asset, state whether that level intentionally falls back to Graphics settings or still needs explicit assignment. + - Do not claim all quality levels are migrated unless each relevant level has been inspected. + - If using serialized project settings, the saved field is commonly `customRenderPipeline`; writing a guessed field such as `renderPipelineAsset` is not enough unless the saved asset proves the assignment. + - If assigning through script, use the same pattern as URP's Render Settings converter: cache `QualitySettings.GetQualityLevel()`, call `QualitySettings.SetQualityLevel(index)` for each target level, assign `QualitySettings.renderPipeline = urpAsset`, then restore the original quality level and verify on disk. +2. **Check URP asset settings** that commonly affect parity: + - shadows + - shadow distance and cascades + - MSAA + - render scale + - HDR, opaque texture, and depth texture settings when effects depend on them +3. **Do not promise identical lighting automatically.** + - Built-in and URP can differ in light falloff, baked GI appearance, shadow tuning, reflection probe response, tonemapping, exposure, and post-processing behavior. +4. **For baked lighting scenes,** treat existing lightmaps and Lighting Data as reference material, not guaranteed-final URP output. + - Inventory `Lightmapping.lightingSettings`, scene `LightmapSettings`, baked/mixed lights, light probes, reflection probes, and any existing `LightingDataAsset`. + - Preserve baked data until the user has a visual reference or rollback point, but do not keep stale Built-in lightmaps active as the final URP lighting solution if they blow out or distort the scene. + - If the scene looks blown out, too dark, or mismatched, first isolate post-processing/exposure by disabling legacy PPv2 during URP validation, then review URP Volume exposure/tonemapping/bloom before changing lights. + - If clearing baked data makes the scene stop being blown out, identify the old lightmaps/Lighting Data as stale or incompatible active data. Then rebake under URP with the final URP asset, renderer, Volume, and Quality settings instead of tuning lights against the stale bake. + - If creating or assigning URP-compatible `LightingSettings`, mark the lighting settings and active scene dirty, save the scene, reload or re-query, and verify the saved scene references the intended `.lighting` asset. `AssetDatabase.SaveAssets()` alone does not save the scene's `Lightmapping.lightingSettings` reference. Do not report "Baked GI enabled" if the saved scene still points at an Enlighten/realtime-GI settings asset. + - When visual parity is part of the request and old `LightingData.asset` / reflection-probe EXRs remain from the Built-in bake, treat them as reference data until rebaked/refreshed under URP. Do not claim visual parity is preserved from old bake data alone. + - Recommend clearing/rebaking lighting and refreshing reflection probes when visual parity matters. Do not claim baked lighting was successfully migrated unless a representative scene has been visually checked after URP setup, and preferably after a URP bake. +5. **For 2D lighting projects,** ensure sprites and tilemaps use URP-compatible lit materials where required. +6. **For performance regressions,** inspect whether the issue is coming from: + - heavier URP asset settings + - post-processing + - extra shadow cost + - custom shader ports or non-batched shaders +7. **When changing URP asset settings,** re-read the saved asset or query the property after saving before reporting values such as MSAA, additional-light limits, HDR, depth texture, or opaque texture. + +## 10. Validation + +After setup, conversion, or troubleshooting, validate the result: + +1. **Capture the scene:** Capture the Scene View or a specific camera on a representative scene — see [capturing-the-editor.md](capturing-the-editor.md). +2. **Evaluate the result:** + - no magenta materials unless unresolved custom shader blockers remain + - main lighting and shadows behave as expected + - baked GI/lightmaps, light probes, and reflection probes are acceptable or explicitly marked for rebake/refresh + - cameras render expected content + - post-processing or fullscreen effects still behave correctly + - sprites, tilemaps, or 2D lights work when relevant +3. **Verify persistent project data, not only visual output.** + - Inspect saved URP assets, renderer assets, scene references, material shader GUIDs/names, Quality settings, and Volume profiles. + - Confirm the representative scene, not a default/test scene, was opened or otherwise inspected before concluding that baked lighting, PPv2, or reflection probes are absent. + - For material migration, include particle/VFX materials in the verification. Remaining built-in particle shader IDs or legacy particle shader names mean material migration is incomplete. + - For PPv2 migrations, saved URP `VolumeProfile` assets must contain the expected override components before reporting them as migrated. + - If a tool log reports mapped post-processing but the saved profile reloads with `components: []`, override the tool log and report the migration as failed/incomplete. + - For baked-lighting scenes, inspect Lighting Settings, Lighting Data/lightmap references, light probes, and reflection probes. Compilation success does not prove baked lighting parity. If old lightmaps cause overexposure, clear active baked data and rebake under URP before judging parity. After assigning new lighting settings, verify the saved scene reference, not only the existence of the new `.lighting` asset. + - If old `LightingData.asset` remains assigned and reflection-probe EXRs were not regenerated or explicitly accepted after visual inspection, classify lighting/probes as preserved or partial rather than refreshed. +4. **Check Console output** with `Unity.GetConsoleLogs` for shader, render pipeline, or renderer-feature errors. +5. **Fix the highest-impact issue first,** then validate again. +6. **Repeat for at most 3 iterations** before reporting remaining blockers or asking the user how they want to proceed. + +## 11. Troubleshooting Decision Tree + +If the user reports a migration problem, follow this diagnostic flow: + +### Project still behaves like Built-in after "migration" +1. Check whether a URP asset is assigned in Graphics settings. +2. Check whether the relevant Quality levels also point to a URP asset. +3. Verify that the active render pipeline is actually URP before troubleshooting anything else. + +### Migration stopped after installing URP +1. Treat this as a package-refresh/domain-reload boundary, not a failed full migration by itself. +2. Re-check `Packages/manifest.json` and package state. If URP is installed, do not reinstall it. +3. Inspect for partial assets such as URP assets, renderer assets, converted materials, empty Volume profiles, and scene component changes. +4. If URP is installed/assigned but Built-in materials still dominate or the scene is magenta, material conversion is the immediate next incomplete item. Do not call URP setup complete and stop there if rollback safety has already been confirmed. +5. Continue from the first incomplete verification item: Graphics/Quality assignment, renderer asset validity, material conversion, PPv2-to-URP Volume migration, baked-lighting rebake, then final validation. +6. If the previous chat/export has no final response, report it as incomplete evidence and continue in a fresh chat/turn. + +### Materials are magenta / bright pink +1. Check Console and Inspector for shader errors. +2. Confirm whether the material uses a supported Built-in shader, a custom shader, or a package-owned shader. +3. If it is a supported Built-in shader, review the converter path or targeted material conversion first. +4. If the project is already on URP and many supported Built-in materials remain, treat this as incomplete material conversion, not as final visual parity work. +5. If it is a custom or package shader, move into [custom-shader-triage.md](custom-shader-triage.md) and, when needed, [complex-shader-situations.md](complex-shader-situations.md). + +### Scene is much darker, brighter, or just "wrong" +1. Compare Scene View and Game View captures. +2. Check for double post-processing first: retained PPv2 `PostProcessVolume` / `PostProcessLayer` plus an active URP `Volume` can overexpose or otherwise distort validation captures. +3. Review shadows, ambient/environment lighting, tone mapping, skybox, exposure, bloom, and post-processing. +4. Inspect baked lighting state: Lighting Settings, Lighting Data asset, lightmap references, mixed/baked lights, light probes, and reflection probes. +5. Review quality-level assignments and URP asset settings before rewriting content. +6. If clearing baked data fixes severe overexposure, treat the old lightmaps as stale active data: keep them only as reference/rollback evidence, then rebake under URP. +7. If the scene depends on baked lighting, recommend a URP rebake and reflection-probe refresh before claiming visual parity. +8. Remember that Built-in and URP light falloff can differ; treat that as a tuning task, not proof that conversion failed. + +### Post-processing or fullscreen effects disappeared +1. Check whether PPv2 was converted and whether the target camera and volume setup are still valid. +2. Inspect saved URP `VolumeProfile` assets. Empty profiles mean PPv2 effects were not actually migrated. +3. Check whether old `PostProcessVolume` / `PostProcessLayer` components remain active in scenes. +4. Search for `OnRenderImage`, custom blit code, or replacement-shader camera effects. +5. Port the effect using a URP-compatible approach rather than trying to preserve the Built-in callback path unchanged. + +### Transparent / refraction / distortion effects broke +1. Inspect whether the shader relied on `GrabPass` or a similar Built-in screen-copy workflow. +2. If so, use [complex-shader-situations.md](complex-shader-situations.md) and choose a Scene Color / Renderer Feature / custom-pass approach. + +### 2D lights are not affecting sprites +1. Confirm the project is actually using the 2D Renderer. +2. Confirm existing sprite materials were upgraded to URP-compatible lit materials where needed. +3. Do not assume dragged-in new sprites prove old project materials are correct. + +### Performance regressed after migration +1. Review render scale, shadows, additional lights, MSAA, post-processing, opaque/depth textures, and other URP asset settings. +2. Check whether custom shader ports lost batching compatibility or introduced extra passes. +3. Tune settings before assuming the only answer is a rollback. + +### Custom shader compiles but visuals are still wrong +1. Determine whether the issue is simple parameter drift or a structural incompatibility. +2. If the shader came from a surface shader, `GrabPass`, replacement-shader workflow, or custom lighting path, treat it as a complex migration case. +3. Validate one representative material before rolling the approach out project-wide. diff --git a/skills/using-unity/references/migrate-birp-to-urp/references/quality-settings-map.md b/skills/using-unity/references/migrate-birp-to-urp/references/quality-settings-map.md index e1f6b99..7271b54 100644 --- a/skills/using-unity/references/migrate-birp-to-urp/references/quality-settings-map.md +++ b/skills/using-unity/references/migrate-birp-to-urp/references/quality-settings-map.md @@ -4,10 +4,12 @@ Use this map to explain where common Built-in quality settings end up after URP ## Official References -- [Convert Built-in quality settings to URP](https://docs.unity3d.com/Manual/urp/birp-onboarding/quality-presets.html) -- [Find Built-in quality settings in URP](https://docs.unity3d.com/Manual/urp/birp-onboarding/quality-settings-location.html) -- [Universal Render Pipeline asset](https://docs.unity3d.com/Manual/urp/urp-asset-and-renderer.html) -- [Change how lights fade to match the Built-In Render Pipeline](https://docs.unity3d.com/Manual/urp/birp-onboarding/birp-light-falloff-in-urp.html) +Read each page's local copy from `<editor-install>/Editor/Data/Documentation/en/Manual/<local file>` (or `en/ScriptReference/` for API pages) when it exists, otherwise the online `.md` page. Replace `<VERSION>` with the project's Unity version, e.g. `6000.3`. + +- [Convert Built-in quality settings to URP](https://docs.unity.com/en-us/engine/<VERSION>/manual/render-pipelines/universal-render-pipeline/introduction/installing-and-configuring-urp/upgrading-from-birp/quality-presets.md) — local `urp/birp-onboarding/quality-presets.html` +- [Find Built-in quality settings in URP](https://docs.unity.com/en-us/engine/<VERSION>/manual/render-pipelines/universal-render-pipeline/introduction/installing-and-configuring-urp/upgrading-from-birp/quality-settings-location.md) — local `urp/birp-onboarding/quality-settings-location.html` +- [Universal Render Pipeline asset](https://docs.unity.com/en-us/engine/<VERSION>/manual/render-pipelines/universal-render-pipeline/urp-quality-settings/urp-asset-and-renderer.md) — local `urp/urp-asset-and-renderer.html` +- [Change how lights fade to match the Built-In Render Pipeline](https://docs.unity.com/en-us/engine/<VERSION>/manual/render-pipelines/universal-render-pipeline/introduction/installing-and-configuring-urp/upgrading-from-birp/birp-light-falloff-in-urp.md) — local `urp/birp-onboarding/birp-light-falloff-in-urp.html` ## Common Mappings diff --git a/skills/using-unity/references/migrate-birp-to-urp/references/setup-and-conversion.md b/skills/using-unity/references/migrate-birp-to-urp/references/setup-and-conversion.md new file mode 100644 index 0000000..220a3f4 --- /dev/null +++ b/skills/using-unity/references/migrate-birp-to-urp/references/setup-and-conversion.md @@ -0,0 +1,141 @@ +# Setup and Conversion + +Choosing the migration path, setting up URP, converting materials, and triaging shaders, post-processing, and camera effects. + +Links to other reference files point to files in this `references/` folder. Any other relative paths resolve to the skill directory. + +## Contents + +- 4. Choose the Migration Path +- 5. URP Setup Workflow +- 6. Conversion Workflow +- 7. Shader and Material Triage +- 8. Post-Processing, Cameras, and Rendering-Effect Triage + +## 4. Choose the Migration Path + +Use the correct path for the project: + +### Path A: Standard 3D Built-in to URP +- Use this for normal 3D Built-in projects moving to standard URP. + +### Path B: Built-in 2D to URP 2D +- Use this when the project is primarily 2D and the user expects URP 2D lighting or renderer behavior. +- Do not treat this as the same workflow as standard URP. + +### Path C: Targeted Material-Only Conversion +- Use this only when the project is already on URP and the user wants selected materials converted. + +### Path D: Troubleshooting an Existing Migration +- Use this when the project is already on URP or the migration has already been attempted. +- Prioritize the highest-impact breakages instead of re-running the entire migration blindly. + +## 5. URP Setup Workflow + +Follow this exact setup order: + +1. **Ensure URP is installed.** + - Installing URP can trigger package refresh, compilation, and domain reload. Treat this as a phase boundary. + - Do not spin-wait indefinitely inside a `script eval` call on `UnityEditor.PackageManager.Client.Add`. Request installation, then verify through `Packages/manifest.json`, package listing, or the presence of URP types/assets after Unity finishes refreshing. + - If the package install causes the `script eval` call to time out or return nothing, resume in a fresh turn after Unity finishes compiling. Do not restart the whole migration or reinstall URP; inspect the partial state and continue from there. +2. **Create the required URP asset and renderer asset** if they do not already exist. +3. **Assign the URP asset in Graphics settings** and in all relevant Quality levels. +4. **For 2D projects,** create and assign the correct 2D Renderer asset before conversion. +5. **If a URP asset already exists,** inspect and reuse it when appropriate instead of creating duplicates automatically. +6. **Do not continue** until URP is actually the active render pipeline for the target configuration. + +## 6. Conversion Workflow + +For actual conversion work, follow [migration-workflow.md](migration-workflow.md). + +1. **Choose the correct Render Pipeline Converter path:** + - `Built-in Render Pipeline to URP` + - `Built-in Render Pipeline 2D to URP 2D` +2. **Initialize converters and inspect the candidate changes** before converting. +3. **For standard Built-in to URP migration,** prefer the applicable converters described in the reference: + - `Rendering Settings` + - `Material Upgrade` + - `Animation Clip Converter` + - `Read-only Material Converter` + - `Post-processing Stack v2 Converter` +4. **For selected-material conversion,** use the targeted material conversion workflow instead of converting the whole project. +5. **Review warnings and failures before converting.** +6. **Run the conversion only after the user confirms the project is safe to change.** +7. **Verify which shader each material actually landed on** — do not assume the converter chose the 3D + target. `MaterialUpgrader.FetchAllUpgradersForPipeline` returns the 2D provider set alongside the 3D + one, and both claim `Standard` at equal priority, so on a 3D project a plain `Standard` material can + silently convert to `Universal Render Pipeline/2D/Mesh2D-Lit-Default` instead of + `Universal Render Pipeline/Lit`. Nothing errors and the material does not go magenta, so this is + invisible unless you read the shader name back — measured on 6000.5.8f1. + + Read every converted material's `shader.name` afterwards and confirm it matches the intended target + from the mapping table. If any landed on a `2D/` shader in a 3D project, restore those materials from + the rollback point and convert them with a 3D-filtered upgrader list, or with the manual pattern in + [implementation-patterns.md](implementation-patterns.md). +7. **After conversion, verify the saved project state.** + - Re-open or re-query representative assets instead of trusting command output alone. + - Save both assets and open scenes after scene-level edits. Changes to scene components, camera data, active lighting settings, reflection probes, and PPv2 enable states are not proven by `AssetDatabase.SaveAssets()` alone. + - Confirm the URP asset is assigned in Graphics and intended Quality levels. + - For Quality levels, validate by re-querying `QualitySettings.GetRenderPipelineAssetAt(i)` or by reading the saved `customRenderPipeline` entries in `ProjectSettings/QualitySettings.asset`. If they remain `{fileID: 0}`, the Quality levels are not explicitly assigned. + - Do not call a guessed quality API such as `QualitySettings.SetRenderPipelineAssetAt`; in Unity versions where that API is unavailable, switch to each target level with `QualitySettings.SetQualityLevel(index)`, set `QualitySettings.renderPipeline = urpAsset`, then restore the original level and verify the saved `customRenderPipeline` values. + - Confirm converted materials actually reference URP shaders. + - Confirm representative materials that had source albedo textures now have non-null `_BaseMap` values. This check must compare against a pre-conversion material snapshot; do not use post-conversion `_MainTex` as the source of truth. + - Confirm particle/VFX materials no longer reference Built-in particle shader IDs or legacy shader names; use URP particle shaders such as `Universal Render Pipeline/Particles/Unlit` where appropriate. If material names or paths include `Particle`, `Fog`, `Smoke`, `Steam`, `VFX`, `Additive`, or similar effect terms, preserve transparent/additive behavior rather than defaulting them to URP Lit. + - Confirm vegetation materials preserve cutout/alpha clipping, render face intent, textures, tint, normals, and expected wind/billboard behavior. If grass/tree cards become solid or static because their specialized shader behavior was lost, material conversion is partial. + - If PPv2 conversion was attempted, confirm saved URP Volume profiles contain persistent non-null `components` entries and the scene/camera wiring uses URP-compatible components. + - If baked lighting exists, preserve the old Lighting Data and lightmaps as reference data, then verify whether they still produce acceptable URP visuals. If a new Lighting Settings asset is created, verify the saved scene actually references it after saving/reloading; the asset existing on disk is not enough. In an actual generic migration, attempt rebaking/refreshing when stale baked data or reflection probes affect parity; if that cannot finish in the current turn, report the migration as partial and resume from the lighting/probe phase later. + - Do not claim "refreshed reflection probes" from intent. Verify new or updated probe outputs, changed saved reflection-probe assets, or successful probe-render tool output. If the existing EXR files remain unchanged, say probes were preserved as reference or still need refresh. + - If any verification fails, report the item as incomplete/manual follow-up, not as migrated. + +## 7. Shader and Material Triage + +When materials are magenta, shaders fail to compile, or visuals drift heavily, use [custom-shader-triage.md](custom-shader-triage.md) first. + +1. **Identify affected materials and shaders.** + - Inspect the exact material shader assignments, not just scene symptoms. +2. **Read Console and Inspector errors before editing shader code.** +3. **Classify the shader case:** + - supported Built-in shaders that the converter should handle + - simple custom shaders that might be ported safely + - complex custom shaders that need a scoped migration plan + - foliage/vegetation shaders that require cutout, two-sided leaves, billboards, terrain detail rendering, or wind behavior + - package-owned or Asset Store shaders that may require maintainer documentation, scoped custom porting, or manual follow-up +4. **For complex shader situations,** use [complex-shader-situations.md](complex-shader-situations.md). +5. **Prefer the smallest safe fix.** + - Restore rendering on representative materials first. + - Validate the result before scaling the fix to more assets. +6. **Never bulk search-and-replace shader code across the whole project** unless the mapping is explicit, tested, and scoped. + +## 8. Post-Processing, Cameras, and Rendering-Effect Triage + +Built-in projects often rely on more than material conversion. + +1. **If PPv2 is present,** inspect the converter output and validate the resulting URP volumes, profiles, and camera behavior. + - Inventory existing `PostProcessVolume`, `PostProcessLayer`, and PPv2 `PostProcessProfile` assets before conversion. + - Prefer the URP `Post-processing Stack v2 Converter` when available instead of hand-building equivalent profiles from memory. + - After conversion, verify that saved URP `VolumeProfile` assets contain persistent override components, not an empty `components: []` profile or dangling `{fileID: 0}` component references. + - If creating a profile by script, `VolumeProfile.Add<T>()` only creates a component object; for persistent profile assets, also call `AssetDatabase.AddObjectToAsset(component, profile)`, mark the profile and component dirty, save assets, reload the asset, and count saved non-null components before reporting success. If the saved profile has `{fileID: 0}` component entries, recreate or repair the profile before claiming migration success. + - Verify representative scenes contain the intended `Volume` objects and that target cameras have `UniversalAdditionalCameraData` with post-processing enabled when required. + - If the source scene still only serializes a PPv2 `sharedProfile` reference and no URP `Volume` references the new `VolumeProfile`, PPv2 migration is incomplete even if a URP profile asset exists on disk. + - If an active URP `Volume` references an empty profile, treat that as incomplete scene wiring, not as active post-processing. Repair the profile or report PPv2 as partial. + - Check whether old `PostProcessVolume` / `PostProcessLayer` components remain. If they remain, explain whether they are intentionally retained, harmless legacy leftovers, or unresolved migration work. + - If old PPv2 components are retained only as reference while a URP Volume is active, disable the old PPv2 component/layer for URP visual validation to avoid double post-processing. Do not delete it until parity is accepted or the user approves cleanup. + - Do not remove PPv2 packages, components, or profiles as a cleanup step until a verified URP replacement exists or the user accepts that those effects will be dropped/manual follow-up. + - During an actual migration, do not leave common PPv2 parity as a vague manual task if the source profile is available. Create persistent URP overrides for common mappable effects such as Bloom, Color Adjustments/Tonemapping, Vignette, and Depth of Field, then verify the saved profile has non-null components. + - It is acceptable to mark unsupported or non-equivalent effects as manual follow-up, such as PPv2 Screen Space Reflections or Ambient Occlusion that should become a renderer feature / SSAO setup instead of a direct Volume override. + - If URP Volume overrides cannot be created reliably, document the PPv2 effects and their URP equivalents instead of claiming they were migrated. +2. **Do not treat transient tool success as post-processing success.** + - A command log that says "Added Bloom" is not enough. Re-read the saved `VolumeProfile` asset or inspect the scene after saving/reloading. + - If the saved profile is empty, say the PPv2 setup was documented or partially prepared, not migrated. +3. **If grep finds `OnRenderImage`,** treat it as a custom full-screen effect case. + - In URP, custom full-screen effects should move toward `ScriptableRenderPass`, a Renderer Feature, or URP custom post-processing instead of staying on the Built-in image-effect path. +4. **If grep finds `RenderWithShader` or `SetReplacementShader`,** treat it as a replacement-shader case. + - These effects often need a deliberate URP renderer-feature or custom-pass strategy. +5. **If an effect depends on scene color, depth, or normals,** verify the URP-compatible path rather than assuming the Built-in approach still applies. +6. **If custom cameras were stacking effects in Built-in,** validate camera output explicitly after migration instead of assuming parity. +7. **For advanced shader/effect troubleshooting questions, provide concrete replacement patterns.** + - For `GrabPass`, mention `_CameraOpaqueTexture` / Scene Color, the required URP asset setting, and the limitation that transparent ordering can differ from Built-in. + - For `OnRenderImage`, mention `ScriptableRendererFeature` plus `ScriptableRenderPass`. When showing a Unity 6-style template, use the reference pattern with a temporary `RTHandle` and `Blitter.BlitCameraTexture`. + - Never recommend `Blitter.BlitCameraTexture(cmd, source, source, material, pass)` or other source-to-source blits as the main `OnRenderImage` replacement. If you are not going to show the safer temporary-target pattern, omit the code sample and explain the architecture instead. + - For Surface Shaders, state that `#pragma surface` has no direct URP equivalent and choose Shader Graph or a URP HLSL vertex/fragment rewrite based on effect complexity. + - Do not stop at "rewrite it"; give the user a practical first porting step and a validation target. diff --git a/skills/using-unity/references/optimize-audio/optimize-audio.md b/skills/using-unity/references/optimize-audio/optimize-audio.md index 22a9459..4dbe03a 100644 --- a/skills/using-unity/references/optimize-audio/optimize-audio.md +++ b/skills/using-unity/references/optimize-audio/optimize-audio.md @@ -2,14 +2,66 @@ name: optimize-audio description: Optimizes audio memory, CPU cost, and playback quality through import settings and mixer configuration. Use when asked to reduce audio memory or Audio Mixer CPU cost, change clip Load Types, sample rates or codecs, or force 3D audio to mono. --- -## Critical Rules - -- Do not make changes before reporting findings to the user -- Follow steps in strict order; never jump ahead -- STOP at every `WAIT` checkpoint and await the user's response before continuing -- Quality is more important than speed: measure before and after every change +## Important + +- Use the unity cli (`unity command --format json`) and the `unity-cli` and `unity-pipeline` skills for each step. +- Before making changes, establish a baseline so you can tell whether a later result is caused by your change. +- Create a restore point you can roll back to if your changes fail. +- Do only what's asked. Don't change unrelated assets or files. +- Never leave verification code in the user's script. Never build logging or detection they didn't ask for. +- Avoid long explanations. +- Do not make changes before reporting findings to the user, because import and mixer settings apply to every scene that uses the clip or mixer. +- Follow steps in strict order; never jump ahead, because each step uses what the previous one found. +- STOP at every `WAIT` checkpoint and await the user's response before continuing, because the user decides which changes to make. - Always verify results in a device build; Editor audio stats are indicative only +## Full topic map + +Before you go forward with a workflow or diagnosis: + +1. Read the [documentation page(s)](#full-topic-map) covering what you intend to do or fix, and check if you've missed anything. +2. Name the file(s) you read in your response. + +Your training knowledge about Unity may be out of date, incorrect, or for the wrong version. + +Prefer `WebFetch` over `WebSearch` — faster and lands on the exact reference. Only fetch what you need. Replace `<VERSION>` with the following before fetching: + +- **docs.unity3d.com** (the `xrefmap.yml` and `ScriptReference` URLs): The Editor version, for example `6000.0`. This isn't a package version. +- **docs.unity.com**: The product version, eg `7000.0` + +Read the Unity version from `ProjectSettings/ProjectVersion.txt`. + +If `<editor-install>/Editor/Data/Documentation/en/Manual` exists, read the local html file named below from it. Otherwise fetch the online `.md` page. + +- **Audio Clip Import Settings reference** — `class-AudioClip.html`, [online](https://docs.unity.com/en-us/engine/<VERSION>/manual/audio/reference/class-audio-clip.md): every clip import setting. +- **Audio file compression** — `AudioFiles-compression.html`, [online](https://docs.unity.com/en-us/engine/<VERSION>/manual/audio/files/compression.md): size, CPU and quality cost of each format. +- **Audio settings** — `class-AudioManager.html`, [online](https://docs.unity.com/en-us/engine/<VERSION>/manual/unity-editor/editor-settings-reference/comp-manager-group/class-audio-manager.md): DSP Buffer Size. +- **Audio Mixer** — `AudioMixer.html`, [online](https://docs.unity.com/en-us/engine/<VERSION>/manual/audio/mixer.md): mixer groups, effects and snapshots. +- **Audio Mixer inspectors** — `AudioMixerInspectors.html`, [online](https://docs.unity.com/en-us/engine/<VERSION>/manual/audio/mixer/inspectors.md): effect CPU display, Auto Mixer Suspend. +- **Audio Source** — `class-AudioSource.html`, [online](https://docs.unity.com/en-us/engine/<VERSION>/manual/audio/reference/class-audio-source.md): Spatial Blend, rolloff, Output. +- **Audio Listener** — `class-AudioListener.html`, [online](https://docs.unity.com/en-us/engine/<VERSION>/manual/audio/reference/class-audio-listener.md): listener behaviour. +- **Audio Profiler module** — `ProfilerAudio.html`, [online](https://docs.unity.com/en-us/engine/<VERSION>/manual/audio/profiler.md): measuring audio memory and DSP CPU. + +### API reference + +The API is `UnityEditor.AudioImporter` and the `UnityEngine` audio classes, part of the Unity Engine. It is versioned by Unity version, so check the project's Unity version before relying on a specific class or method. + +1. Use the `unity-cli` skill to check the project's Unity version. +2. If `<editor-install>/Editor/Data/Documentation/en/ScriptReference` exists, grep its html files and skip the remaining steps. +3. Otherwise, fetch and cache `https://docs.unity3d.com/<VERSION>/Documentation/ScriptReference/xrefmap.yml`. This file lists every public API member's fully qualified name as a `uid` (e.g. `uid: 'UnityEditor.AudioImporter.forceToMono'`). +4. Grep the yml file locally for a class or method instead of refetching per lookup. The file is large (about 6 MB), so don't read the whole file. +5. Convert the `uid` to a markdown page: remove the parameters in brackets, lowercase it, replace `.` with `/`, and add `.md`. Then fetch `https://docs.unity.com/en-us/engine/<VERSION>/script-reference/<converted uid>`. For example, `UnityEngine.AudioClip.LoadAudioData` => `https://docs.unity.com/en-us/engine/<VERSION>/script-reference/unityengine/audioclip/loadaudiodata.md`. All overloads are on the same page. + - Constructors use `ctor`, and indexers use `item`. For operators, fetch the class page and follow its link. + - Links inside the pages start with `/engine/`. Add `https://docs.unity.com/en-us` before them. + - If the page doesn't exist for that Unity version, use the `href` in the `xrefmap.yml` entry instead (e.g. `href: 'AudioImporter.html'` => `https://docs.unity3d.com/<VERSION>/Documentation/ScriptReference/AudioImporter.html`). + +Always use the docs for the project's Unity version rather than relying on training knowledge, since APIs are frequently marked obsolete between versions. Pages this skill uses: + +- [AudioImporter](https://docs.unity.com/en-us/engine/<VERSION>/script-reference/unityeditor/audioimporter.md): `forceToMono`, `loadInBackground`. +- [AudioImporterSampleSettings](https://docs.unity.com/en-us/engine/<VERSION>/script-reference/unityeditor/audioimportersamplesettings.md): per-platform sample settings. +- [AssetImporter.SaveAndReimport](https://docs.unity.com/en-us/engine/<VERSION>/script-reference/unityeditor/assetimporter/saveandreimport.md): applying importer changes. +- [AudioSettings.GetDSPBufferSize](https://docs.unity.com/en-us/engine/<VERSION>/script-reference/unityengine/audiosettings/getdspbuffersize.md): DSP buffer size. + ## 0. Set up the execution path Every C# step below runs inside a live Editor through the Unity CLI. **The `unity-cli` skill owns @@ -27,39 +79,39 @@ Two things it can't know for you: edit metadata directly. Run C# with `unity command script eval --caller plugin --skill optimize-audio --code '<snippet>'`. Discover the parameter shape from -`unity command --format json` rather than assuming one. `unity command` defaults to a 30 second -timeout. +`unity command --format json` rather than assuming one. `script eval`'s default timeout depends on the +Pipeline version, so read it from that schema and pass `--timeout <seconds>` for a slow call. ### Passing C# to `script eval` -`script eval` compiles a **statement block, not a file**. Two consequences, both of which cause a compile -error rather than a warning: +`script eval` compiles a **statement block, not a file**, so write the code without `using` directives and with fully qualified types. If the code doesn't compile, look up the error here: -- **No `using` directives.** The compiler reads `using UnityEngine;` as a resource-disposal - statement and rejects it (`CS0210`). -- **Types must be fully qualified.** A bare `AssetDatabase` or `AudioImporter` does not resolve - (`CS0246` / `CS0103`), and a bare `Object` is ambiguous with `object` (`CS0104`). +| Error | Cause | Fix | +| --- | --- | --- | +| `CS0210` | A `using` directive, which the compiler reads as a resource-disposal statement | Remove the directive and qualify the types | +| `CS0246` / `CS0103` | An unqualified type, such as `AssetDatabase` or `AudioImporter` | Use the full name, such as `UnityEditor.AssetDatabase` or `UnityEditor.AudioImporter` | +| `CS0104` | A bare `Object`, which is ambiguous with `object` | Use `UnityEngine.Object` | -The recipes in [resources/audio-import-api.md](resources/audio-import-api.md) are written -fully qualified so they can be passed to `script eval` as-is. +Every recipe named below is in [references/audio-import-api.md](references/audio-import-api.md), +written fully qualified so it can be passed to `script eval` as-is. ## 1. Pre-Flight: Detect Audio System Before doing anything else, establish the audio environment: -1. **Detect platform and sample rate:** Use `script eval` to read `EditorUserBuildSettings.activeBuildTarget` and `AudioSettings.outputSampleRate`. The output sample rate affects whether overriding clip sample rates will actually save memory. -2. **Detect AudioMixer presence:** Use the mixer-asset query recipe in [resources/audio-import-api.md](resources/audio-import-api.md) to see if a mixer graph exists. If none exists, note that routing and effect costs are not a concern. -3. **Detect AudioListener:** Use the scene-component query recipe in [resources/audio-import-api.md](resources/audio-import-api.md) for `UnityEngine.AudioListener` to confirm exactly one listener is present. Multiple listeners produce incorrect spatialization; zero listeners produce silence. +1. **Detect platform and sample rate:** Use `script eval` to read `EditorUserBuildSettings.activeBuildTarget` and `AudioSettings.outputSampleRate`. Note that `AudioSettings.outputSampleRate` reflects the Editor host device's rate, not the target platform's rate — use it as a rough guide only and measure on-device to confirm. Clips above the output sample rate are usually resampled down when they play, so they gain no quality from the extra samples. Such clips should only be flagged for review, because they could be used for slow playback creatively. +2. **Detect AudioMixer presence:** Use the mixer-asset query recipe to see if a mixer graph exists. If none exists, note that routing and effect costs are not a concern. +3. **Detect AudioListener:** Use the scene-component query recipe for `UnityEngine.AudioListener` to confirm exactly one listener is present. The docs say each scene can only have one Audio Listener to work properly, and with none, nothing is heard. Offer to add one to the main camera, or disable extras. 4. **Proceed** only after platform and listener state are confirmed. ## 2. Assess Current State Before recommending any change, gather observable data: -1. **Find all AudioSources:** Use the scene-component query recipe in [resources/audio-import-api.md](resources/audio-import-api.md) for `UnityEngine.AudioSource`. For each result, use **one** `script eval` call to batch-read properties — see the batch read recipe in [resources/audio-import-api.md](resources/audio-import-api.md). -2. **Inspect mixer topology:** If a mixer was found in Pre-Flight, use `script eval` to read the AudioMixer's exposed parameters and group count. A group count above ~8 or effects on the Master group are immediate flags. -3. **Check DSP buffer size:** Use the DSP buffer recipe in [resources/audio-import-api.md](resources/audio-import-api.md) to read buffer size. See DSP Buffer Size Guidelines in [resources/platform-settings.md](resources/platform-settings.md) for recommended values. -4. **Report findings before making changes:** Summarize ALL detected sources, the listener count, and mixer depth to the user. Flag any immediate risks (e.g., stereo clip with `spatialBlend = 1`, Decompress On Load on a clip > 1 MB, reverb on the Master group). +1. **Find all AudioSources:** Use the scene-component query recipe for `UnityEngine.AudioSource`. For each result, use **one** `script eval` call to batch-read properties — see the batch read recipe. +2. **Inspect mixer topology:** If a mixer was found in Pre-Flight, use `script eval` to count its groups with `AudioMixer.FindMatchingGroups(string.Empty)`. For the tree and effects, read the `.mixer` asset file as text, because the public `AudioMixer` API can't list groups or effects: each `AudioMixerGroupController` lists its `m_Children` and `m_Effects`, and each `AudioMixerEffectController` has an `m_EffectName`. If the file isn't text (Asset Serialization isn't Force Text), ask the user to describe the group tree and effects from the Audio Mixer window. Also read `m_EnableSuspend` and `m_SuspendThreshold` (Auto Mixer Suspend). An effect costs the same at any tree level and depth adds no cost, so look for effects repeated across groups. +3. **Check DSP buffer size:** Use the DSP buffer recipe to read buffer size. See DSP Buffer Size Guidelines in [references/platform-settings.md](references/platform-settings.md) for recommended values. +4. **Report findings before making changes:** Summarize ALL detected sources, the listener count, and mixer effects to the user. Flag any immediate risks (e.g., stereo clip with `spatialBlend = 1`, Decompress On Load on a long clip that will expand to a large PCM footprint, an effect duplicated across sibling groups, Auto Mixer Suspend off). **WAIT for the user to review the assessment before proceeding.** @@ -71,9 +123,9 @@ Route to the correct section based on what the user needs: |-----------|------| | "audio memory too high" / "memory profiler shows audio" | Section 4 — Import settings audit | | "load times slow" / "decompression stall" | Section 4 — Load Type review | -| "DSP spike" / "mixer CPU" / "audio CPU high" | Section 4B — Mixer audit | +| "DSP spike" / "mixer CPU" / "audio CPU high" / "crackling" / "audio popping" / "dropouts" | Section 4B — Mixer audit (audio thread overload) | | "3D sound wrong" / "only left channel plays" / "stereo in 3D" | Section 4A — Force To Mono + spatial settings | -| "quality artifacts" / "voice sounds bad" / "Vorbis crackling" | Section 4C — Compression quality tuning | +| "quality sounds compressed" / "voice sounds muffled" | Section 4C — Compression quality tuning | | "mobile audio battery" / "mobile memory" | Section 4D — Mobile sample rate override | | "set import settings on all clips" / "batch audio settings" | Section 4 — Bulk import audit | | "streaming" / "background loading" / "Addressables audio" | Section 4E — Streaming and async load | @@ -88,112 +140,90 @@ Use the findings from Section 2 to determine which sub-section applies. More tha For any AudioSource where `spatialBlend > 0` (3D positioned sound): -1. **Check clip channel count:** Use `script eval` to read `audioSource.clip.channels`. If `channels == 2` and `spatialBlend == 1`, only the left channel plays — this is a bug, not a feature. -2. **Recommend Force To Mono:** Use the read importer recipe in [resources/audio-import-api.md](resources/audio-import-api.md) to inspect current settings, then apply Force To Mono using the force-to-mono recipe. -3. **Apply and reimport:** Report before/after channel counts to the user. +1. **Check clip channel count and spread:** Use `script eval` to read `audioSource.clip.channels`, `audioSource.spatialBlend`, and `audioSource.spread`. If `channels == 2` and `spatialBlend == 1` and `spread == 0`, the second channel only costs memory: at Spread 0, a 3D source plays all channels from the same point, which is mono. If Spread > 0 or if `spatialBlend < 1` (partially 3D or fully 2D), the clip should remain stereo. +2. **Recommend Force To Mono:** Use the read importer recipe to inspect current settings. Before recommending Force To Mono, warn the user that it is a per-clip import setting applied to every platform — if the same clip is used as 2D on one platform and 3D on another, forcing it to mono removes stereo everywhere. Then recommend Force To Mono only for stereo clips on fully 3D sources (spatialBlend == 1) with zero Spread. + + **WAIT for the user to approve the changes before applying.** + +3. **Apply and reimport:** Apply Force To Mono with the force-to-mono recipe, then report before/after channel counts to the user. 4. **Verify spatial blend:** Use `script eval` to confirm `audioSource.spatialBlend` is `1.0` (full 3D) and `audioSource.rolloffMode` is set to an appropriate curve. ### 4B. AudioMixer Audit -1. **Measure group depth:** Use `script eval` to walk the mixer's group tree and count levels. More than 3 levels (Master → SFX / Music / Voice → sub-bus) adds routing overhead every frame, even when children are silent. -2. **Check effects on silent groups:** Use `script eval` to query each group's effects list. Effects such as `AudioReverbFilter` run their DSP at full cost even when no AudioSource routes to that group. -3. **Flag SFX Reverb on parent groups:** This is the most expensive built-in effect. If found on the Master or a high-level group, flag it explicitly. +1. **Find duplicated effects:** List effects repeated across sibling groups. One instance on the shared parent is cheaper, but only for **linear** effects (see [references/troubleshooting.md](references/troubleshooting.md)), because a compressor or distortion on the combined signal changes the mix. +2. **Check Auto Mixer Suspend:** With `m_EnableSuspend: 0`, effects keep processing after all sources stop. When enabled, the mixer suspends once no source plays into it and its output is below `m_SuspendThreshold`, so flag sources that keep playing silently (such as a looping source at volume 0). +3. **Measure per-effect cost:** Don't guess which effect is most expensive. Ask the user to enable **Enable FMOD Profiling** (**Preferences** > **Diagnostics** > **Audio**), choose **Toggle CPU usage display** from an AudioGroup Inspector's gear menu, and report each effect's CPU. 4. **Present recommendations to the user:** - - Remove or bypass effects on groups that have no active sources. - - Use **snapshots** to switch mix states (combat / explore / pause) rather than toggling effects at runtime. - - Flatten unnecessary sub-buses; redirect sources to a shallower ancestor. + - Apply duplicated linear effects once on their shared parent. + - Enable Auto Mixer Suspend; a Threshold Volume above −80 dB suspends sooner. + - Bypass effects the mix doesn't need. + - Use **snapshots** to switch mix states (combat / explore / pause) rather than toggling effects at runtime. To stop effect processing via snapshot, enable Allow Wet Mixing on the effect and set its wet level to −80 dB in the target snapshot; a snapshot transition alone silences but does not stop processing. **WAIT for the user to approve the mixer changes before applying.** -5. **Verify DSP buffer size:** If `bufferLength` from Pre-Flight is very small (< 256), recommend increasing it — see DSP Buffer Size Guidelines in [resources/platform-settings.md](resources/platform-settings.md). + Make approved mixer changes in the Audio Mixer window, or ask the user to, because there's no public API for groups and effects and hand-editing the `.mixer` file can corrupt it. + +5. **Verify DSP buffer size:** If `bufferLength` from Section 2 is very small (< 256), recommend increasing it — see DSP Buffer Size Guidelines in [references/platform-settings.md](references/platform-settings.md). ### 4C. Compression Quality Tuning -1. **Read current compression format:** Use the read importer recipe in [resources/audio-import-api.md](resources/audio-import-api.md) to read `compressionFormat` and `quality` for the clips reported by the user. -2. **Apply the platform matrix:** See the Compression Format Matrix in [resources/platform-settings.md](resources/platform-settings.md) for per-platform recommendations. -3. **Warn about lossy sources:** Use the lossy source check recipe in [resources/audio-import-api.md](resources/audio-import-api.md). If the original file is MP3, warn the user that lossy source quality is lost permanently after Unity re-encodes. Recommend WAV or AIFF sources. +1. **Read current compression format:** Use the read importer recipe to read `compressionFormat` and `quality` for the clips reported by the user. +2. **Compare with the platform matrix:** See the Compression Format Matrix in [references/platform-settings.md](references/platform-settings.md) for per-platform recommendations. +3. **Warn about lossy sources:** Use the lossy source check recipe. If the original file is MP3, warn the user that lossy source quality is lost permanently after Unity re-encodes. Recommend WAV or AIFF sources. +4. **Recommend changes:** Report the format and quality you recommend for each clip. + + **WAIT for the user to approve the changes before applying.** + +5. **Apply:** Use the compression format and quality recipe. ### 4D. Mobile Sample Rate Override 1. **Identify SFX clips on mobile target:** Use the scene-component query recipe for `UnityEngine.AudioSource` and filter for non-music, non-dialogue clips. -2. **Read current sample rate setting:** Use the read importer recipe in [resources/audio-import-api.md](resources/audio-import-api.md) to read `sampleRateSetting` and `sampleRateOverride` for each clip. -3. **Apply mobile override:** Use the sample rate override recipe in [resources/audio-import-api.md](resources/audio-import-api.md). See Sample Rate Recommendations in [resources/platform-settings.md](resources/platform-settings.md) for per-use-case rates. +2. **Read current sample rate setting:** Use the read importer recipe to read `sampleRateSetting` and `sampleRateOverride` for each clip, and recommend a rate for each from Sample Rate Recommendations in [references/platform-settings.md](references/platform-settings.md). + + **WAIT for the user to approve the changes before applying.** + +3. **Apply mobile override:** Apply the approved rates with the sample rate override recipe. 4. **Report savings:** Halving the sample rate halves the PCM memory cost. Report the estimated saving for each clip changed. ### 4E. Load Type and Streaming 1. **Audit Load Type per clip:** Use `script eval` to read `clip.loadType` for each clip found in Section 2. -2. **Apply the decision rule:** See Load Type Decision Table in [resources/platform-settings.md](resources/platform-settings.md). -3. **Flag mismatches:** See Load Type Mismatch Flags in [resources/platform-settings.md](resources/platform-settings.md). Report both types of mismatches to the user. -4. **Apply `Load In Background`** for any Streaming clip — use the Load In Background recipe in [resources/audio-import-api.md](resources/audio-import-api.md). +2. **Compare with the decision rule:** See Load Type Decision Table in [references/platform-settings.md](references/platform-settings.md). +3. **Flag mismatches:** See Load Type Mismatch Flags in [references/platform-settings.md](references/platform-settings.md). Report both types of mismatches to the user, with the Load Type you recommend for each clip. -## 5. Validation + **WAIT for the user to approve the changes before applying.** -After any import setting or mixer change: - -1. **Re-read clip stats:** Use `script eval` to re-read `clip.loadType`, `clip.channels`, `AudioSettings.outputSampleRate`, and the importer's `compressionFormat` to confirm the change applied after reimport. -2. **Confirm AudioSource routing:** Use the scene-component query recipe for `UnityEngine.AudioSource` and verify `audioSource.outputAudioMixerGroup` is assigned as expected after any mixer restructure. -3. **Report delta:** State the before and after values for each setting changed. Do not assume the change was effective without reading back the applied importer values. -4. **Iterate limit:** Maximum 3 adjust-and-verify cycles before pausing to ask the user for feedback. +4. **Apply:** Set each approved Load Type with the Set Load Type recipe. Use the Load In Background recipe only for Decompress On Load or Compressed In Memory clips whose load stalls the main thread; Streaming clips already load in the background. -## 6. Troubleshooting +## 5. Troubleshooting -### Stereo clip on a 3D AudioSource — only left channel audible +Read [references/troubleshooting.md](references/troubleshooting.md) when the user reports one of these symptoms: a stereo clip on a 3D source, a memory spike from Decompress On Load, a DSP CPU spike, Vorbis artifacts on dialogue, or silence on first play with Load In Background. -1. Confirm `audioSource.spatialBlend == 1`. -2. Confirm `audioSource.clip.channels == 2`. -3. Enable `forceToMono` in the AudioClip importer and reimport. Unity mixes both channels to mono during import, preserving level with `normalize = true` (keep on). -4. If the user does not want to reimport: set `audioSource.panStereo = 0` as a runtime workaround, but warn this does not recover stereo information. - -### Decompress On Load clip causes memory spike - -1. Confirm `clip.loadType == AudioClipLoadType.DecompressOnLoad` and `clip.length` is long (> 5 s). -2. Switch to `Streaming` if it is music or ambience, `CompressedInMemory` if played only occasionally. -3. If the clip is short but still large: check `clip.channels` (stereo wastes double the memory) and `clip.frequency` (high sample rate on a mobile target wastes memory). Apply Force To Mono and/or sample rate override. - -### AudioMixer CPU spike — DSP thread hot - -1. Confirm with the mixer-asset query recipe that the mixer graph exists. -2. Use `script eval` to list all groups and their attached effects. Look for reverb, chorus, or EQ on high-level groups. -3. Move expensive effects down to leaf groups that are only active when sources are playing. -4. Use snapshots to bypass effect chains during gameplay states where they are not heard (e.g., bypass reverb during a menu). -5. If the DSP buffer is small (64 or 128 samples), raise it — see DSP Buffer Size Guidelines in [resources/platform-settings.md](resources/platform-settings.md). +## See Also -### Vorbis quality artifacts on dialogue +- `route-audio-to-mixer-groups` — creating mixers and routing Audio Sources into groups. -1. Confirm `defaultSampleSettings.compressionFormat == AudioCompressionFormat.Vorbis`. -2. Confirm `defaultSampleSettings.quality` — default is 0.5, which is often audible on voice. Raise to 0.7–0.85. -3. On iOS: switch to AAC instead of Vorbis (hardware decode, better quality at equivalent bitrate). -4. Confirm the source file is lossless (WAV or AIFF). MP3 sources cannot recover quality lost before Unity's re-encode. +## Final step -### AudioListener count is not exactly one +After any import setting or mixer change: -- **Zero listeners:** All audio will be silent. Use `script eval` to add an `AudioListener` component to the main camera: `UnityEngine.Camera.main.gameObject.AddComponent<UnityEngine.AudioListener>()`. -- **Multiple listeners:** Unity uses the last enabled one, producing unpredictable spatialization. Use the scene-component query recipe for `UnityEngine.AudioListener` and disable all but the intended one. +1. **Re-read clip stats:** Use `script eval` to re-read `clip.loadType`, `clip.channels`, `AudioSettings.outputSampleRate`, and the importer's `compressionFormat` to confirm the change applied after reimport. +2. **Confirm AudioSource routing:** Use the scene-component query recipe for `UnityEngine.AudioSource` and verify `audioSource.outputAudioMixerGroup` is assigned as expected after any mixer restructure. +3. **Report delta:** State the before and after values for each setting changed. Do not assume the change was effective without reading back the applied importer values. +4. **Iterate limit:** Maximum 3 adjust-and-verify cycles before pausing to ask the user for feedback. -### `Load In Background` causes first-play silence +Check for zero console errors using `console status`. If any check fails, go back and reread the [docs pages](#full-topic-map) to find out what you missed. -This is expected behavior: the clip has not finished loading when `Play()` is first called. Mitigate with: -1. Preload the clip at scene start by calling `clip.LoadAudioData()` before it is needed. -2. Use `AudioSource.PlayScheduled()` with a slight delay to allow async load to complete. -3. For AudioSources that must play immediately: switch to `CompressedInMemory` (synchronous on first play) rather than `Streaming` with background load. +Unless the user asks for additional proof, continue to the [Final report](#final-report). If you suspect a runtime fault, enter Play mode once and read state through `script eval`. Do not add logging or take screenshots. -## 7. Completion +## Final report -After finishing the audit or optimization: +After finishing the audit or optimization, report to the user: - Summarize every setting changed with before/after values. - List any clips or groups that still need attention (e.g., clips that require on-device measurement to confirm savings). +- Disclose any side effects beyond the requested changes, such as reimports triggered or assets touched that the user didn't name, so the user can review them before committing. +- State any follow-up the user needs to do, such as testing on the target device or committing the changed `.meta` and mixer files. - If the user needs runtime memory measurement, point them at the Memory Profiler package, which reports the largest AudioClips by runtime byte cost. - If mixer CPU is still high after the audit, point them at the Unity Profiler's Audio module for DSP thread profiling. - -## Detailed References - -- **Platform settings, compression matrix, load types, sample rates:** [resources/platform-settings.md](resources/platform-settings.md) -- **AudioImporter API recipes and code patterns:** [resources/audio-import-api.md](resources/audio-import-api.md) - -## See Also - -- **Memory Profiler package** — finds the largest AudioClips by runtime byte cost. -- **Unity Profiler, Audio module** — DSP CPU markers and frame-time budget. -- `audio-setup-mixers` — creating mixers and routing Audio Sources into groups. diff --git a/skills/using-unity/references/optimize-audio/resources/audio-import-api.md b/skills/using-unity/references/optimize-audio/references/audio-import-api.md similarity index 86% rename from skills/using-unity/references/optimize-audio/resources/audio-import-api.md rename to skills/using-unity/references/optimize-audio/references/audio-import-api.md index 6509340..c875901 100644 --- a/skills/using-unity/references/optimize-audio/resources/audio-import-api.md +++ b/skills/using-unity/references/optimize-audio/references/audio-import-api.md @@ -1,5 +1,12 @@ # Audio Import API Recipes +## Contents + +- Read AudioClip Importer Settings; Force To Mono and Reimport; Set Load Type; Enable Load In Background +- Set Compression Format and Quality; Override Sample Rate (Mobile); Read AudioSource Properties (Batch) +- Read DSP Buffer Size; Check Source File Format (Lossy Warning); Resolving `audioSource` / `clip` inside a snippet +- Enumerate scene components; Enumerate mixer assets + C# code recipes for `unity command script eval --caller plugin --skill optimize-audio --code '<snippet>'`. All examples target the Unity 6 AudioImporter API. @@ -16,7 +23,7 @@ return $"forceToMono={importer.forceToMono}, loadType={importer.defaultSampleSet $"compressionFormat={importer.defaultSampleSettings.compressionFormat}, " + $"quality={importer.defaultSampleSettings.quality}, " + $"sampleRateSetting={importer.defaultSampleSettings.sampleRateSetting}, " + - $"sampleRateOverride={importer.defaultSampleSettings.sampleRateOverride}"); + $"sampleRateOverride={importer.defaultSampleSettings.sampleRateOverride}"; ``` ## Force To Mono and Reimport @@ -26,7 +33,7 @@ var path = UnityEditor.AssetDatabase.GetAssetPath(audioSource.clip); var importer = (UnityEditor.AudioImporter)UnityEditor.AssetImporter.GetAtPath(path); importer.forceToMono = true; importer.SaveAndReimport(); -return $"Reimported {path} — channels now: {audioSource.clip.channels}"); +return $"Reimported {path} — channels now: {audioSource.clip.channels}"; ``` ## Set Load Type @@ -56,7 +63,7 @@ var path = UnityEditor.AssetDatabase.GetAssetPath(audioSource.clip); var importer = (UnityEditor.AudioImporter)UnityEditor.AssetImporter.GetAtPath(path); var settings = importer.defaultSampleSettings; settings.compressionFormat = UnityEngine.AudioCompressionFormat.Vorbis; -settings.quality = 0.7f; // 0.0–1.0; raise to 0.7–0.85 for dialogue +settings.quality = 0.7f; // 0.0–1.0; tune per clip — quality is not linear importer.defaultSampleSettings = settings; importer.SaveAndReimport(); ``` @@ -83,14 +90,14 @@ return $"clip={src.clip?.name}, loadType={src.clip?.loadType}, " + $"channels={src.clip?.channels}, frequency={src.clip?.frequency}, " + $"spatialBlend={src.spatialBlend}, rolloff={src.rolloffMode}, " + $"mixerGroup={src.outputAudioMixerGroup?.name ?? "None"}, " + - $"bypassEffects={src.bypassEffects}"); + $"bypassEffects={src.bypassEffects}"; ``` ## Read DSP Buffer Size ```csharp UnityEngine.AudioSettings.GetDSPBufferSize(out int bufferLength, out int numBuffers); -return $"DSP buffer: {bufferLength} samples x {numBuffers} buffers"); +return $"DSP buffer: {bufferLength} samples x {numBuffers} buffers"; ``` ## Check Source File Format (Lossy Warning) @@ -98,7 +105,9 @@ return $"DSP buffer: {bufferLength} samples x {numBuffers} buffers"); ```csharp var path = UnityEditor.AssetDatabase.GetAssetPath(clip); if (path.EndsWith(".mp3", System.StringComparison.OrdinalIgnoreCase)) - return $"'{clip.name}' is MP3 — lossy source quality is lost permanently after Unity re-encodes. Recommend WAV or AIFF sources."); + return $"'{clip.name}' is MP3 — lossy source quality is lost permanently after Unity re-encodes. Recommend WAV or AIFF sources."; +if (path.EndsWith(".ogg", System.StringComparison.OrdinalIgnoreCase)) + return $"'{clip.name}' is OGG — lossy source quality is lost permanently after Unity re-encodes. Recommend WAV or AIFF sources."; ``` ## Resolving `audioSource` / `clip` inside a snippet @@ -124,8 +133,8 @@ var clip = UnityEditor.AssetDatabase.LoadAssetAtPath<UnityEngine.AudioClip>("Ass ## Enumerate scene components Substitute the component type (`UnityEngine.AudioSource`, `UnityEngine.AudioListener`). Inactive -objects are included deliberately — a disabled second listener still counts against the -one-listener rule. +objects are included so the count shows every listener. Before you treat a listener as a +duplicate, check its `enabled` and `gameObject.activeInHierarchy`. ```csharp var found = UnityEngine.Object.FindObjectsByType<UnityEngine.AudioSource>( diff --git a/skills/using-unity/references/optimize-audio/references/platform-settings.md b/skills/using-unity/references/optimize-audio/references/platform-settings.md new file mode 100644 index 0000000..da2f400 --- /dev/null +++ b/skills/using-unity/references/optimize-audio/references/platform-settings.md @@ -0,0 +1,32 @@ +# Audio Platform Settings Reference + +## Compression Format + +See [Audio file compression](https://docs.unity.com/en-us/engine/<VERSION>/manual/audio/files/compression.md) for the full format-by-platform table and CPU/size/quality trade-offs. + +Skill-specific notes: +- Quality is not linear, so it needs tuning per clip by ear. You can't hear the clip, so don't pick a final value yourself: recommend a starting value, ask the user to play the clip in the Editor and report audible artifacts (crackle, a warbling or metallic tone, or blurred transients such as smeared consonants or drum hits), and adjust from their reports. Lower quality until the user hears artifacts, then raise it slightly. +- MP3 pads loops with silence; use lossless WAV or AIFF source assets instead. + +## Sample Rate + +See [Audio Clip Import Settings](https://docs.unity.com/en-us/engine/<VERSION>/manual/audio/reference/class-audio-clip.md) for sample rate settings. + +Halving the sample rate halves the PCM memory cost. Always report the estimated saving for each clip changed. + +## Load Type + +See [Audio Clip Import Settings](https://docs.unity.com/en-us/engine/<VERSION>/manual/audio/reference/class-audio-clip.md) for Load Type behavior. + +### Load Type Mismatch Flags + +- **Decompress On Load** on a long clip bloats memory: the full PCM expands in RAM at load time. Estimate the footprint as `clip.samples × clip.channels × 2` bytes (16-bit PCM) and report it. +- **Streaming** on a clip that plays dozens of times simultaneously adds disk pressure. +- **Load In Background** applies to Decompress On Load and Compressed In Memory clips: loading no longer stalls the main thread, but a `Play()` call before loading finishes is delayed. Streaming clips already load in the background, so the setting has no effect on them. +- For clips that must play immediately, enable **Preload Audio Data** in the clip's import settings so the clip loads with the scene, or call `clip.LoadAudioData()` before it's needed. + +## DSP Buffer Size + +See [Audio settings](https://docs.unity.com/en-us/engine/<VERSION>/manual/unity-editor/editor-settings-reference/comp-manager-group/class-audio-manager.md) for DSP Buffer Size options. + +If `bufferLength` < 256, recommend increasing to Good Latency (512) or Best Performance (1024) to trade latency for CPU stability. diff --git a/skills/using-unity/references/optimize-audio/references/troubleshooting.md b/skills/using-unity/references/optimize-audio/references/troubleshooting.md new file mode 100644 index 0000000..5d269b0 --- /dev/null +++ b/skills/using-unity/references/optimize-audio/references/troubleshooting.md @@ -0,0 +1,35 @@ +# Troubleshooting + +Links to other reference files point to files in this `references/` folder. Any other relative paths resolve to the skill directory. + +### Stereo clip on a 3D AudioSource + +1. Confirm `audioSource.spatialBlend == 1`. +2. Confirm `audioSource.clip.channels == 2`. +3. Confirm `audioSource.spread` is 0 (the default), because then the source plays all channels from one point and the second channel only costs memory. +4. Enable `forceToMono` in the AudioClip importer and reimport. Unity mixes both channels to mono during import. If clip levels were balanced before import, disable Normalize to preserve relative volumes. Enable Normalize only if the mixed-down result is too quiet. + +### Decompress On Load clip causes memory spike + +1. Confirm `clip.loadType == AudioClipLoadType.DecompressOnLoad` and `clip.length` is long (> 5 s). +2. Switch to `Streaming` if it is music or ambience, `CompressedInMemory` if played only occasionally. +3. If the clip is short but still large: check `clip.channels` (stereo wastes double the memory) and `clip.frequency` (high sample rate on a mobile target wastes memory). Apply Force To Mono and/or sample rate override. + +### AudioMixer CPU spike — DSP thread hot + +1. Confirm with the mixer-asset query recipe that the mixer graph exists. +2. List all groups and their attached effects from the `.mixer` file, as described in Section 2 of the skill. Look for the same effect repeated across groups. An effect costs the same wherever it sits in the tree. +3. Find groups under a common parent that share the same **linear** effect, and suggest applying the effect once on the parent. Effects don't declare linearity, so judge from the effect name: equalizers and filters can be reordered among each other without changing the result, but a compressor, gate, limiter or distortion anywhere in the chain makes the result depend on the combined signal, so keep those on their original groups. +4. If the DSP buffer is small (64 or 128 samples), raise it — see DSP Buffer Size Guidelines in [references/platform-settings.md](platform-settings.md). + +### Vorbis quality artifacts on dialogue + +1. Confirm `defaultSampleSettings.compressionFormat == AudioCompressionFormat.Vorbis`. +2. Read `defaultSampleSettings.quality` (0–1) and the platform override, if one is enabled. You can't hear the clip, so tune with the user: raise quality a step, ask the user to play the clip in the Editor and say whether the crackle or warble is gone, and repeat. Once it's gone, offer to lower quality a step at a time until they hear it return, then go back one step. Quality is not linear, so tune each clip separately. +3. Confirm the source file is lossless (WAV or AIFF). MP3 sources cannot recover quality lost before Unity's re-encode. + +### `Load In Background` causes first-play silence + +This is expected behavior: the clip has not finished loading when `Play()` is first called. Mitigate with: +1. Enable **Preload Audio Data** in the clip's import settings so it loads with the scene, or call `clip.LoadAudioData()` before the clip is needed. +2. If the clip must play the moment it's triggered and can't be preloaded, disable Load In Background on that clip so it loads synchronously, and warn the user that synchronous loading can stall the main thread. diff --git a/skills/using-unity/references/optimize-audio/resources/platform-settings.md b/skills/using-unity/references/optimize-audio/resources/platform-settings.md deleted file mode 100644 index bf4b785..0000000 --- a/skills/using-unity/references/optimize-audio/resources/platform-settings.md +++ /dev/null @@ -1,48 +0,0 @@ -# Audio Platform Settings Reference - -## Compression Format Matrix - -| Platform | Recommended Format | Notes | -|---|---|---| -| PC / cross-platform | Vorbis, quality 0.5–0.7 | Raise to 0.7–0.85 for dialogue; default 0.5 often adds artifacts | -| iOS | AAC | Hardware decode; cheapest CPU | -| Android | Vorbis | Software decode | -| Xbox | XMA | Use platform override in import settings | -| PlayStation | ATRAC9 | Use platform override in import settings | -| Web | Vorbis | Browser handles decode | - -## Sample Rate Recommendations - -| Use Case | Recommended Rate | -|---|---| -| PC / console music and voice | 44100 Hz | -| PC / console SFX | 44100 Hz | -| Mobile SFX | 22050 Hz | -| Mobile dialogue | 22050 or 44100 Hz | -| UI clicks / blips | 22050 Hz | - -Halving the sample rate halves the PCM memory cost. Always report the estimated saving for each clip changed. - -## Load Type Decision Table - -| Load Type | Behavior | Use For | -|---|---|---| -| Decompress On Load | PCM in memory at load; zero per-play CPU | Short SFX < 200 KB (uncompressed) | -| Compressed In Memory | Stays compressed; decompresses on play | Medium clips played occasionally | -| Streaming | Streams from disk; minimal RAM, higher disk I/O | Music, long ambience, voice-overs | - -### Load Type Mismatch Flags - -- **Decompress On Load** on a clip > 1 MB bloats memory. -- **Streaming** on a clip that plays dozens of times simultaneously adds disk pressure. -- Always apply `Load In Background` for any Streaming clip to prevent the main thread stalling on first play. - -## DSP Buffer Size Guidelines - -| Setting | Buffer Size | Use Case | -|---|---|---| -| Best Latency | 256 | Rhythm games, real-time synthesis | -| Good Latency | 512 | General gameplay | -| Best Performance | 1024 | Ambient/cinematic, battery-saving | - -A very small buffer (64 or 128) costs more CPU per frame. If `bufferLength` is < 256, recommend increasing to "Good Latency" or "Best Performance" to trade latency for CPU stability. diff --git a/skills/using-unity/references/optimize-text-mesh-pro/SECURITY.md b/skills/using-unity/references/optimize-text-mesh-pro/SECURITY.md new file mode 100644 index 0000000..78d918d --- /dev/null +++ b/skills/using-unity/references/optimize-text-mesh-pro/SECURITY.md @@ -0,0 +1,15 @@ +# Security notes: optimize-text-mesh-pro + +This skill can have the agent run C# in the user's live Unity Editor with `unity command script eval`, to read project and Play mode state while it optimizes or checks TextMesh Pro usage. Automated skill scanners flag running code in the Editor as a powerful capability. It is intentional, and it is limited by the safeguards below. + +## Accepted risks + +| Risk | Capability | Why it is accepted | +|---|---|---| +| `SEC_POWER_CAP` | Runs C# in the user's live Editor through `unity command script eval` | It only reaches the Editor the user already has open, on their own machine, as that user, so it grants nothing they couldn't do themselves. | + +## Mitigations + +- **Only the user's own Editor.** The code runs in the Editor open on this machine. It can't reach another machine or another user's Editor. +- **Nothing left behind.** The skill tells the agent never to leave verification code in the user's scripts, and to create a restore point before changes. +- **No remote code.** Nothing downloaded from outside is executed. diff --git a/skills/using-unity/references/optimize-text-mesh-pro/optimize-text-mesh-pro.md b/skills/using-unity/references/optimize-text-mesh-pro/optimize-text-mesh-pro.md index a3fd4fd..9e22c5d 100644 --- a/skills/using-unity/references/optimize-text-mesh-pro/optimize-text-mesh-pro.md +++ b/skills/using-unity/references/optimize-text-mesh-pro/optimize-text-mesh-pro.md @@ -10,7 +10,7 @@ description: Optimizes TextMeshPro rendering, memory, and font setup, including - Use the unity cli (`unity command --format json`) and the `unity-cli` and `unity-pipeline` skills for each step. - Create a restore point you can roll back to if your changes fail. - Do only what's asked. Don't change unrelated assets or files. -- Don't use `using` directives or unqualified types in the `snippet` for `eval`. The compiler reads `using UnityEngine` and a bare `AssetDatabase`, `Volume`, or `Object` causes errors (CS0246 / CS0103 / CS0104). `return` what you want to read; it arrives at `data.result.result`. +- Run C# with `unity command script eval --caller plugin --skill optimize-text-mesh-pro --code '<snippet>'`. Don't use `using` directives or unqualified types in the snippet. The compiler reads `using UnityEngine` and a bare `AssetDatabase`, `Volume`, or `Object` causes errors (CS0246 / CS0103 / CS0104). `return` what you want to read; it arrives at `data.result.result`. - Never leave verification code in the user's script; never build logging or detection they didn't ask for. See [Final step](#final-step). - Avoid long explanations. @@ -208,9 +208,9 @@ Always fetch the version matching the installed package rather than relying on t Do the following checks: -1. Check the project has zero console errors. Use `console_status` for counts. +1. Check the project has zero console errors. Use `console status` for counts. 2. Stop there unless the user asked you to prove it works or you suspect a specific fault. -3. If you do enter Play mode, do it once only to chase a fault you already suspect. Read the world through `eval` rather than adding logging. Take no screenshots as they take too much time. +3. If you do enter Play mode, do it once only to chase a fault you already suspect. Read the world through `script eval` rather than adding logging. Take no screenshots as they take too much time. If a check fails, go back and reread the [docs pages](#full-topic-map) to find out what you missed. diff --git a/skills/using-unity/references/optimize-web/optimize-web.md b/skills/using-unity/references/optimize-web/optimize-web.md index ef7cb2b..d0b3075 100644 --- a/skills/using-unity/references/optimize-web/optimize-web.md +++ b/skills/using-unity/references/optimize-web/optimize-web.md @@ -13,10 +13,6 @@ Audit and apply the Player Settings, compression, stripping, and server setup th - If the changes affect runtime behavior, add `Debug.Log` lines that will prove the actual scene behaviour (not just your changes) is now working - you'll read these when you enter Play mode to validate later. For example, log a GameObject's Transform scale if your fix is meant to make sure it changes size. - Avoid long explanations. -## Performance Notes -- Take your time to do this thoroughly. -- Quality is more important than speed. - ## Full topic map Before you go forward with a workflow or diagnosis: @@ -81,141 +77,29 @@ The KTX API (`KtxUnity`) is part of the `com.unity.cloud.ktx` package. It is ver ## Running C# in the Editor -Every step below that reads or writes a Player Setting runs inside a live Editor through the Unity -CLI. **The `unity-cli` skill owns getting you there** — installing the CLI, confirming a connected -Editor, adding the project's `com.unity.pipeline` package, telling a genuinely absent Editor apart -from one stuck in Safe Mode, and discovering the Editor's command catalog. Follow it first; don't -re-derive any of it here. - -Two things it can't know for you: - -- **You need `script eval` in particular**, not just a reachable Editor. Confirm it appears in the catalog. - Its presence depends on the Pipeline package version, not on the CLI, so a healthy install can - still lack it — if it's missing, say so and skip the steps that read or write settings. -- **You can read Player Settings from `ProjectSettings/ProjectSettings.asset` in a pinch, but do not - write them that way.** The serialized names don't match the API names, several of these settings - are per-build-target, and a hand-edited value silently disagrees with what the build actually - uses. An unreachable Editor is a stop for the write steps. - -Run C# with `unity command script eval --caller plugin --skill optimize-web --code '<snippet>'`. `unity command` defaults to a 30 second -timeout. - -### Passing C# to `script eval` - -`script eval` compiles a **statement block, not a file**, so write the code without `using` directives and -with fully qualified types. If the code doesn't compile, look up the error here: - -| Error | Cause | Fix | -| --- | --- | --- | -| `CS0210` | A `using` directive, such as `using UnityEditor;`, which the compiler reads as a resource-disposal statement | Remove the directive and qualify the types | -| `CS0246` | An unqualified type, such as `PlayerSettings` | Use the full name, such as `UnityEditor.PlayerSettings` | -| `CS0104` | A bare `Object`, which is ambiguous with `object` | Use `UnityEngine.Object` | - -### Reading the settings this skill audits - -One call returns the whole Pre-Flight picture. Verified against Unity 6000.5.7f1: - -```csharp -var target = UnityEditor.Build.NamedBuildTarget.WebGL; -var w = new System.Collections.Generic.List<string>(); -w.Add($"activeBuildTarget={UnityEditor.EditorUserBuildSettings.activeBuildTarget}"); -w.Add($"compressionFormat={UnityEditor.PlayerSettings.WebGL.compressionFormat}"); -w.Add($"decompressionFallback={UnityEditor.PlayerSettings.WebGL.decompressionFallback}"); -w.Add($"stripEngineCode={UnityEditor.PlayerSettings.stripEngineCode}"); -w.Add($"managedStrippingLevel={UnityEditor.PlayerSettings.GetManagedStrippingLevel(target)}"); -w.Add($"il2cppCodeGeneration={UnityEditor.PlayerSettings.GetIl2CppCodeGeneration(target)}"); -w.Add($"apiCompatibilityLevel={UnityEditor.PlayerSettings.GetApiCompatibilityLevel(target)}"); -w.Add($"exceptionSupport={UnityEditor.PlayerSettings.WebGL.exceptionSupport}"); -w.Add($"debugSymbolMode={UnityEditor.PlayerSettings.WebGL.debugSymbolMode}"); -w.Add($"dataCaching={UnityEditor.PlayerSettings.WebGL.dataCaching}"); -w.Add($"wasm2023={UnityEditor.PlayerSettings.WebGL.wasm2023}"); -w.Add($"initialMemorySize={UnityEditor.PlayerSettings.WebGL.initialMemorySize}"); -w.Add($"maximumMemorySize={UnityEditor.PlayerSettings.WebGL.maximumMemorySize}"); -w.Add($"memoryGrowthMode={UnityEditor.PlayerSettings.WebGL.memoryGrowthMode}"); -w.Add($"targetFrameRate={UnityEngine.Application.targetFrameRate}"); -w.Add($"vSyncCount={UnityEngine.QualitySettings.vSyncCount}"); -return string.Join("\n", w); -``` - -**Three API names to get right**, because the obvious spellings do not exist and fail to compile: - -| Setting | Correct form | Does NOT exist | -|---|---|---| -| Managed stripping level | `PlayerSettings.GetManagedStrippingLevel(NamedBuildTarget.WebGL)` | `PlayerSettings.managedStrippingLevel` | -| Wasm code optimization | `UnityEditor.WebGL.UserBuildSettings.codeOptimization` | `PlayerSettings.WebGL.codeOptimization`, `PlayerSettings.WebGL.optimizationLevel` | -| IL2CPP code generation | `PlayerSettings.GetIl2CppCodeGeneration(NamedBuildTarget.WebGL)` | a bare property | - -`UserBuildSettings` lives in the WebGL build-support module, so it only resolves when that module is -installed. Read it in a separate call from the rest, and treat a resolution failure as "the Web -module isn't installed" rather than as a bad snippet. - -**`codeOptimization` is the one setting here that does not live in the project file.** It persists to -`Library/EditorUserBuildSettings.asset`, and `Library/` is gitignored by every standard Unity -`.gitignore`, so this value is per-machine and does not travel: teammates and CI do not inherit it. -Two consequences. Read it back through the API and do not look for it in -`ProjectSettings/ProjectSettings.asset` — it is absent there even on a successful apply, so its -absence is not a failure. And if the release build runs in CI, apply it there as a build step rather -than assuming the repository carries it. - -### Applying the settings - -Most of the writes in this skill are a single batch, and -[scripts/WebOptimizer.cs](scripts/WebOptimizer.cs) already is that batch. It declares a class -with a `[MenuItem]`, so it is a **project file, not `script eval` input** — a class declaration cannot be -flattened into a statement block. Save it under `Assets/Editor/`, let Unity compile, then invoke it -in one line: - -```csharp -UnityEditor.EditorApplication.ExecuteMenuItem("Tools/Apply Web Release Settings"); -``` +Every step that reads or writes a Player Setting runs inside a live Editor through the Unity CLI. The `unity-cli` skill owns getting you there: installing the CLI, confirming a connected Editor, adding `com.unity.pipeline`, and telling an absent Editor apart from one stuck in Safe Mode. Follow it first. -Keep its `using` directives; they are correct in a file. For one-off changes — a single quality -level, a frame-rate flip — an inline `script eval` statement is fine. +- Confirm `script eval` appears in the command catalog, because its presence depends on the Pipeline package version. If it's missing, say so and skip the steps that read or write settings. +- Don't write Player Settings by editing `ProjectSettings/ProjectSettings.asset`, because the serialized names don't match the API names, several settings are per build target, and a hand-edited value can disagree with what the build uses. An unreachable Editor is a stop for the write steps. -### Verify from disk, not from the objects you just wrote +Run C# with `unity command script eval --caller plugin --skill optimize-web --code '<snippet>'`. Its default timeout depends on the Pipeline version, so read it from the command's schema (`unity command --detail full --format json`) and pass `--timeout <seconds>` for a slow call. -**Applying a setting and reading it back in the same session proves nothing.** Player Settings are -in-memory objects until something saves them, so every read-back returns the value you just -assigned whether or not it ever reached -`ProjectSettings/ProjectSettings.asset`. A run that skips the save reports success, and when the -Editor session ends the whole change is gone. This was observed, not theorised: a run applied -everything, read back Brotli / High / None, said it was done, and the file on disk never changed. +Before you run any snippet, read [references/editor-scripting.md](references/editor-scripting.md). It has the Pre-Flight snippet that reads every audited setting, the API names that fail to compile when spelled the obvious way, how to apply settings with [scripts/WebOptimizer.cs](scripts/WebOptimizer.cs), and why you must save and verify from disk after every write. -So after any write: - -1. **Save.** `UnityEditor.AssetDatabase.SaveAssets()`. `WebOptimizer.cs` now does this itself; an - inline `script eval` write has to do it explicitly. -2. **Read the values back and report them.** Not "applied successfully" but the actual values, so the - user can see what is stored. `WebOptimizer.cs` logs all nine. -3. **For anything per-build-target, name the target you read.** Several of these settings exist once - per target, so a value can be correct for one target and unset for the one being built. - -The same trap exists on the file-editing route in reverse: a hand-edited -`ProjectSettings.asset` reads back fine while the running Editor and the build still use the old -value. Verifying after a save and a reimport is what catches both. - -**Do not try to reproduce this in batch mode.** A batch Editor invoked with `-quit` saves settings on -exit, so an unsaved write persists anyway and the run looks correct. Both a saving and a non-saving -version of the script pass under `-quit`. The bug only appears in a live Editor session, which is -where it was found. Concluding from a green batch run that the save is unnecessary is the wrong -conclusion from a test that cannot see the defect. ## 0. Pre-Flight -1. **Confirm Web build target:** Read, with the Pre-Flight snippet above, `EditorUserBuildSettings.activeBuildTarget` — must be `WebGL`; if not, warn the user. -2. **Read compression and stripping settings:** Read `compressionFormat`, `decompressionFallback`, `stripEngineCode` and the managed stripping level with the Pre-Flight snippet above. Note the stripping level is `PlayerSettings.GetManagedStrippingLevel(NamedBuildTarget.WebGL)` — there is no `PlayerSettings.managedStrippingLevel` property. -3. **Read exception and optimization settings:** Read `PlayerSettings.WebGL.exceptionSupport` from the Pre-Flight snippet above. For the wasm code optimization level use `UnityEditor.WebGL.UserBuildSettings.codeOptimization` — the `PlayerSettings.WebGL.codeOptimization` and `optimizationLevel` spellings do not exist and will not compile. -4. **Read frame rate settings:** Read, with the Pre-Flight snippet above, `Application.targetFrameRate` and `QualitySettings.vSyncCount`. -5. **Read additional player settings:** Read, with the Pre-Flight snippet above, `PlayerSettings.WebGL.dataCaching`, `PlayerSettings.WebGL.debugSymbolMode`, `PlayerSettings.WebGL.maximumMemorySize`, and `PlayerSettings.GetApiCompatibilityLevel`. -6. Proceed only after you've confirmed the compression, stripping, frame rate, and player settings. +1. Run the Pre-Flight snippet from [references/editor-scripting.md](references/editor-scripting.md#reading-the-settings-this-skill-audits). Read `UnityEditor.WebGL.UserBuildSettings.codeOptimization` in a separate call, because it only resolves when the Web build-support module is installed. +2. Check `activeBuildTarget` is `WebGL`. If not, warn the user. +3. Proceed only after you've recorded the compression, stripping, exception, memory, frame rate and player settings. ## 1. Assess Current State 1. **Check Build Report:** Instruct the user to open `Window > General > Build Report` after a build and identify the largest asset and code size contributors. 2. **Verify server configuration:** Ask the user to confirm whether the hosting server sends `Content-Encoding: br` (Brotli) or `Content-Encoding: gzip` headers, and whether `Content-Type: application/wasm` is set for `.wasm` files. -3. **Check frame rate config:** Confirm, with the Pre-Flight snippet above, `Application.targetFrameRate` — should be `-1` for Web (let the browser drive). -4. **Check memory settings:** Read, with the Pre-Flight snippet above, `PlayerSettings.WebGL.initialMemorySize` and `PlayerSettings.WebGL.memoryGrowthMode`. -5. Report findings before making recommendations. +3. **Check frame rate and memory:** From the Pre-Flight values, `targetFrameRate` should be `-1` for Web (let the browser drive). Note `initialMemorySize` and `memoryGrowthMode`. +4. Report findings before making recommendations. + ## 2. Understand Request @@ -239,254 +123,30 @@ conclusion from a test that cannot see the defect. ## 3. Web Build Optimization Workflow -### IMPORTANT: One-click optimization script - -**Always offer to generate this script for the user.** Unity's official web optimization docs provide a single editor menu script that applies all recommended release settings at once. Place in `Assets/Editor/WebOptimizer.cs` — see [scripts/WebOptimizer.cs](scripts/WebOptimizer.cs) for the template. - -Adapt the script to the user's project needs (e.g. keep exceptions if they use `try/catch`, switch Brotli to Gzip for HTTP hosting). This script is the single most impactful action for a new web project — it prevents settings from being missed. - -### Player Settings audit - -Verify and set these values through `script eval`: - -| Setting | Release recommendation | -|---|---| -| **Compression Format** | **Brotli** (HTTPS hosting); Gzip for HTTP | -| **Decompression Fallback** | **Off** when server is correctly configured | -| **Strip Engine Code** | **On** | -| **Managed Stripping Level** | **High** (release) / Medium (dev) | -| **Code Optimization** | **Disk Size with LTO** (release) / Build Times (dev) | -| **WebAssembly Language Features** | **2023** if browser baseline allows | -| **Enable Exceptions** | **None** (smallest); Explicitly Thrown Only if `try/catch` required | -| **Initial Memory Size** | Tune to peak estimate; too small causes expensive growth | -| **Memory Growth Mode** | **Geometric** | -| **API Compatibility Level** | **.NET Standard 2.1** — smaller than .NET Framework | -| **IL2CPP Code Generation** | **Optimize Size** — smaller Wasm at slight runtime cost | -| **Debug Symbols** | **Off** for release; on for development builds only | -| **Data Caching** | **On** — caches asset data in browser IndexedDB for faster repeat loads | -| **Strip Unused Mesh Components** | **On** — removes unused vertex attributes | -| **Maximum Memory Size** | **2048 MB** default; up to 4096 for complex 3D (Firefox and Chrome < 119 have issues above 2048) | -| **vSyncCount** | 0 (browser handles pacing) | -| **targetFrameRate** | -1 (use `requestAnimationFrame`) | - -### Compression and server configuration - -| Compression | Use when | Notes | -|---|---|---| -| **Brotli** | HTTPS or localhost | Best ratio; browsers accept only over secure contexts | -| **Gzip** | HTTP delivery, legacy CDNs | Universal | -| **None** | Local dev / file:// | Largest payload; do not ship | - -Configure the server to: -- Serve `.br` files with `Content-Encoding: br`. -- Serve `.gz` files with `Content-Encoding: gzip`. -- Set `Content-Type: application/wasm` for `.wasm`, `application/javascript` for `.js`. -- Enable HTTP/2 or HTTP/3 to parallelize chunk fetches. - -If the host cannot inject `Content-Encoding`: set **Decompression Fallback = On** as a fallback only — it adds ~150 KB JS and slows startup. - -### Exception handling - -| Setting | Build size | Use | -|---|---|---| -| **None** | Smallest | Release builds where uncaught exceptions are acceptable | -| **Explicitly Thrown Only** | Modest | Default for projects that catch exceptions | -| **Full** | Largest, slowest | Rarely needed; avoid for release | - -Wasm 2023 introduces a cheaper exception model; switching from Explicitly Thrown Only (legacy) to Wasm exceptions reduces both size and cost when browser targets support it. - -### Remove unused resources - -Three categories to audit for build size reduction: - -**1. Unused packages** — Check `Packages/manifest.json` and the Package Manager **In Project** and **Built-in** views. Remove or disable packages the project does not use. The Input System package is a significant size contributor if unused. - -**2. Shader stripping** — Configure in `Edit > Project Settings > Graphics`: - -| Setting | Recommendation | -|---|---| -| **Lightmap Modes** | Automatic (strips unused lightmap shader variants) | -| **Fog Modes** | Automatic (strips unused fog shader variants) | -| **Instancing Variants** | Strip Unused | -| **Batch Renderer Group Variants** | Strip All (if BRGs are not used) | -| **Always Included Shaders** | Audit and remove any shaders the project does not reference | - -Test after stripping — make sure you didn't remove any referenced shaders. - -**3. Web Stripping Tool** (`com.unity.web.stripping-tool`) — Analyzes the WebAssembly binary and identifies unused Unity engine submodules (e.g. 3D graphics in a 2D-only game). Install via Package Manager, profile the build, then configure which submodules to exclude. Can yield substantial size reductions beyond what Managed Stripping Level achieves alone. - -### Quality settings for Web - -Lower quality levels reduce load time and improve runtime performance. Set via `Edit > Project Settings > Quality`: - -- Use **Very Low** or **Low** as the default Web quality level. -- Set it with `script eval`: `UnityEngine.QualitySettings.SetQualityLevel(0, true);` where 0 = Very Low. -- Consider creating a Web-specific quality level that disables features unnecessary in-browser (real-time shadows, post-processing effects, high particle counts). - -### Frame rate on Web +**Always offer to generate the one-click optimization script.** Unity's web optimization docs provide a single editor menu script that applies all recommended release settings at once. Place it in `Assets/Editor/WebOptimizer.cs`, using [scripts/WebOptimizer.cs](scripts/WebOptimizer.cs) as the template. Adapt it to the project (for example keep exceptions if they use `try/catch`, or switch Brotli to Gzip for HTTP hosting), because it prevents settings from being missed. -- Set it with `script eval`: `UnityEngine.Application.targetFrameRate = -1;` — let the browser use `requestAnimationFrame`. -- Note: **Safari caps at 60 fps** in WebGL; high-refresh targets do not apply. -- Use `OnDemandRendering.renderFrameInterval` to drop to 5–10 fps on static/idle screens to save battery. +For each area the request touches, read its section in [references/optimization-areas.md](references/optimization-areas.md) before you change anything. It covers the Player Settings audit table, compression and server configuration, exception handling, removing unused resources and shader variants, quality settings, frame rate, KTX / Basis Universal textures, streaming, profiling, memory, iOS Safari limits, video and audio, and canvas DPI. -### KTX / Basis Universal textures - -KTX2 with Basis Universal supercompression ships a single texture file that transcodes at load time to the optimal GPU format for the browser's device (BC7 on desktop, ASTC on mobile, ETC2 on older Android). This avoids shipping separate texture variants for each GPU family — critical for Web where the target hardware is unknown. - -| Topic | Guidance | -|---|---| -| **Package** | Install `com.unity.cloud.ktx` (KtxUnity) via Package Manager | -| **When to use** | Runtime-loaded textures via Addressables or asset bundles served to unknown GPU targets | -| **When NOT to use** | Textures baked into the player build — Unity already selects the correct format at build time | -| **Supercompression** | Use **ETC1S** for smallest size (lossy, good for diffuse/albedo); **UASTC** for higher quality (near-lossless, better for normals/UI) | -| **Encoding** | Encode offline with `toktx` or `basisu` CLI; do not encode at runtime | -| **Linear data** | Set `--assign_oetf linear` when encoding normal maps, masks, or data textures to avoid incorrect sRGB conversion | -| **Mip maps** | Generate mips at encode time (`--genmipmap`) — browser-side mip generation is expensive | -| **Loading** | Use `KtxTexture.LoadFromStreamingAssets` or load bytes via UnityWebRequest and call `KtxTexture.LoadFromBytes` | -| **Memory** | Transcoded textures are standard GPU textures; memory cost equals the target format, not the KTX2 file size | -| **Orientation** | Always include `--lower_left_maps_to_s0t0` to match Unity's UV convention | - -**`toktx` CLI examples:** See [scripts/toktx-examples.sh](scripts/toktx-examples.sh) for commands covering albedo (ETC1S), normals/detail (UASTC), ICC profile errors, and linear data. - -### Streaming on Web - -- Use Addressables with **remote groups** hosted on a CDN with Brotli / Gzip. -- Avoid bundling the entire game into the initial download; stream levels on demand. -- Target < 30 MB initial download for "instant play"; level data follows. -- For streamed textures targeting mixed GPU hardware, prefer KTX2 bundles over per-platform variants — one bundle serves all browsers. - -### Profiling Web builds - -| Tool | Use | Notes | -|---|---|---| -| **Chrome DevTools > Performance** | CPU flamegraph; main-thread analysis | Default first stop for WebGL hitches; inspect Wasm call stacks | -| **Chrome DevTools > Memory** | Heap snapshot; allocation timeline | Find JS/Wasm memory leaks; compare snapshots before/after scene load | -| **Firefox Profiler** | Cross-platform; shareable URLs; native + Wasm view | Better Wasm symbolication than Chrome in some cases; shareable profile URLs for team review | -| **Safari Web Inspector** | iOS Safari and macOS Safari debugging | Required for Safari-specific issues; WebGL/Wasm runtime differs from Chromium | -| **Unity Profiler over WebSocket** | Connect to a development build; standard markers | Use for Unity-side markers (GC, rendering, scripts); does not capture browser-side overhead | - -**Symptom → tool quick reference:** - -| Symptom | First-line tool | Second-line tool | -|---|---|---| -| WebGL hitch / stutter | Chrome DevTools > Performance | Firefox Profiler | -| Memory climbing over time | Chrome DevTools > Memory | Unity Memory Profiler (WebSocket) | -| Slow initial load | Chrome DevTools > Network | Build Report Inspector | -| Safari-only rendering issue | Safari Web Inspector | Compare with Chrome DevTools | - -**Embedding profiling symbols** — browser profilers show mangled Wasm function names by default. To get readable C# method names in Chrome/Firefox flamegraphs, either enable `Player Settings > Publishing > Debug Symbols` for dev builds, or add a build processor: - -```csharp -using UnityEditor; -using UnityEditor.Build; -using UnityEditor.Build.Reporting; - -public class WebProfilingBuildProcessor : IPreprocessBuildWithReport -{ - public int callbackOrder => 0; - public void OnPreprocessBuild(BuildReport report) - { - PlayerSettings.SetAdditionalIl2CppArgs("--compiler-flags=--profiling-funcs"); - } -} -``` - -**Emscripten built-in profilers** — enable one at a time via `PlayerSettings.WebGL.emscriptenArgs`: - -| Flag | What it shows | -|---|---| -| `--cpuprofiler` | CPU profiler overlay in browser | -| `--memoryprofiler` | Visual memory map (white=allocated unused, pink=stack, blue=dynamic, green=fragmented) | -| `--threadprofiler` | Thread activity profiler | - -**GPU debugging** — No Frame Debugger support on Web. Use [Spector.js](https://spector.babylonjs.com/) as a browser-based alternative — it captures draw calls and WebGL state. - -**Firefox `about:memory`** — type `about:memory` as a URL in Firefox, click Measure to see per-tab breakdown: WASM code size, WASM heap, .data file, web audio. Watch for WASM heap > 300 MB (crash risk, especially on iOS Safari). - -Editor Play Mode does not represent browser runtime; always measure in browser. Chrome and Safari GC and JIT behavior differ — test both. - -### Web memory directives - -- Disable **Read/Write Enabled** on textures and meshes — it duplicates data into the WASM heap. -- Reduce `.data` file size by moving assets to Addressables or AssetBundles. -- Use compressed texture formats (KTX2/Basis) to reduce both download and decoded memory cost. - -### iOS Safari memory limits - -- **iOS < 18:** WebContent process limit ~1.5 GB. WASM memory (Gigacage) capped at 2 GB. Typed arrays share this pool. On iPhone X (iOS 16) heap growth caps at ~512 MB, but setting Initial Memory Size to 512 MB–1.5 GB upfront works. -- **iOS 18+:** Limits largely lifted; iPhone 11 can allocate ~4 GB. -- On iOS, set **Initial Memory Size** to the target peak rather than relying on growth — Safari handles large upfront allocations better than incremental growth. -- WASM heap > 300 MB risks crashes on older iOS; target < 200 MB for broad compatibility. - -### Video and audio on Web - -- **Video:** Playback only works from a URL (server with CORS enabled) or from StreamingAssets. On iOS the server must support HTTP range requests for streaming. Use browser-compatible formats (MP4/H.264). -- **Audio:** AudioEffects (mixer effects) require compute shaders — **not available on WebGL**. Mixers and MixerGroups work for volume control only. Set audio to **Mono** to improve loading. If `about:memory` shows web audio > 100 MB, audio is likely uncompressed — switch to Vorbis. - -### Canvas and DPI - -If the canvas is scaled up it takes the new resolution. Use `devicePixelRatio` in the web template to offset DPI scaling and avoid rendering at unnecessarily high resolution. ## 4. Validation -1. Re-read the Player Settings with the Pre-Flight snippet (compression, stripping, exceptions, targetFrameRate). +1. Re-read the Player Settings with the Pre-Flight snippet from [references/editor-scripting.md](references/editor-scripting.md) (compression, stripping, exceptions, targetFrameRate). 2. Rebuild the player and compare Build Report file sizes with baseline. 3. Verify in at least Chrome and Safari (GC and JIT behavior differ). 4. Max **3 iterations** before asking the user for feedback. ## 5. Troubleshooting -### Build still large after enabling Strip Engine Code - -1. Is **Managed Stripping Level** set to Medium or Low? → Set to High for release. -2. Are plug-ins using reflection to access engine modules that would otherwise be stripped? → Add a `link.xml` to preserve needed symbols. -3. Is **Exceptions** set to Full? → Full adds the largest code overhead; switch to None or Explicitly Thrown Only. - -### Brotli not working — Decompression Fallback required - -1. Is the server sending `Content-Encoding: br`? → Without this header the browser won't decompress; the fallback JS decompressor is then needed. -2. Is the build hosted over HTTP (not HTTPS)? → Brotli requires a secure context; degrade to Gzip for HTTP hosting. - -### Stutter in Safari but not Chrome - -1. Does the project set `Application.targetFrameRate = 60`? → On Safari WebGL this conflicts with browser pacing; set to `-1`. -2. Are there shaders that behave differently on Safari's WebGL implementation? → Test on device; Safari's WebGL/Wasm runtime differs from Chromium — some GLSL constructs are handled differently. - -### Memory growth slow path triggered - -1. Is **Initial Memory Size** too small for the project's peak? → Wasm memory growth requires a full buffer copy; set Initial Memory Size to a realistic peak estimate. -2. Is **Memory Growth Mode** set to Linear? → Switch to **Geometric** for saner growth curve. - -### Frame rate set to 60 but browser runs erratically - -1. Is `Application.targetFrameRate = 60` set in code? → On Web this conflicts with `requestAnimationFrame` browser pacing. Set to `-1`. -2. Is `vSyncCount` non-zero? → Set to 0; the browser handles pacing. - -### Firefox cache rejecting large files - -Firefox limits individual cache entries via `browser.cache.disk.max_entry_size`. If the build exceeds this (default ~50 MB), assets won't cache. Solution: use Addressables to split into bundles < 51 MB, or instruct users to increase the setting in `about:config`. - -### Local dev server setup - -For testing builds locally with proper MIME types: - -```bash -# Python (HTTP) -python -m http.server 55553 -d path/to/build - -# Node.js (install serve-handler) -npx serve path/to/build -l 3001 -``` +If a symptom persists after the changes, find it in [references/troubleshooting.md](references/troubleshooting.md). It covers builds that stay large, Brotli needing Decompression Fallback, Safari-only stutter, slow memory growth, erratic frame rate, Firefox cache limits, and serving a build locally. -For Brotli testing, use HTTPS — Brotli requires a secure context. Generate a self-signed cert with OpenSSL for local testing. ## Final step Web settings only take effect in a browser build, so a clean compile and Play mode in the Editor aren't enough. Run these checks in order. If any check fails, reread the [docs pages](#full-topic-map) to find out what you missed, fix it, and run the checks again. -1. Check the project has zero console errors. -2. Check that each setting you changed is saved, as described in [Verify from disk](#verify-from-disk-not-from-the-objects-you-just-wrote): `ProjectSettings/ProjectSettings.asset` holds the new values, and `codeOptimization` reads back through the API. -3. If you rebuilt the player, serve the build as described in [Local dev server setup](#local-dev-server-setup) and open it in a browser. Then check the following: +1. Check the project has zero console errors. Use `unity command console status` for counts. +2. Check that each setting you changed is saved, as described in [Verify from disk](references/editor-scripting.md#verify-from-disk-not-from-the-objects-you-just-wrote): `ProjectSettings/ProjectSettings.asset` holds the new values, and `codeOptimization` reads back through the API. +3. If you rebuilt the player, serve the build as described in [Local dev server setup](references/troubleshooting.md#local-dev-server-setup) and open it in a browser. Then check the following: - The browser console shows no errors, such as a failed decompression or an out-of-memory error. - In the Network tab, the `.wasm`, `.data` and `.framework.js` files return the `Content-Encoding` header that matches the compression format (`br` for Brotli, `gzip` for Gzip), and their sizes match the Build Report. 4. If the change affects runtime behaviour, such as the frame rate or quality level, check the `Debug.Log` lines in the browser console, then remove them. Try to avoid taking and checking screenshots unless absolutely necessary, as they take more time. @@ -519,7 +179,7 @@ Point the user at this Unity tooling when the task goes beyond this skill: - **Addressables package** — remote groups served over a CDN, when the download budget needs content moved out of the initial payload. -- **Unity Profiler, connected to the browser** — the cross-platform profiling methodology. Section 3 +- **Unity Profiler, connected to the browser** — the cross-platform profiling methodology. [references/optimization-areas.md](references/optimization-areas.md#profiling-web-builds) covers the Web-specific part of attaching it. - **Shader variant stripping** (Graphics settings → Shader Stripping, and `ShaderVariantCollection`) — variant count feeds directly into Wasm size, so it is worth checking when stripping alone hasn't @@ -527,4 +187,4 @@ Point the user at this Unity tooling when the task goes beyond this skill: - **Project Settings → Player** — the same flags this skill reads, if the user would rather see them in the inspector than have them reported. - Mobile browser battery behaviour follows the same frame-rate and quality-level guidance in - Sections 3 and 4; there is no separate mobile path here. + [references/optimization-areas.md](references/optimization-areas.md); there is no separate mobile path here. diff --git a/skills/using-unity/references/optimize-web/references/editor-scripting.md b/skills/using-unity/references/optimize-web/references/editor-scripting.md new file mode 100644 index 0000000..86eae0b --- /dev/null +++ b/skills/using-unity/references/optimize-web/references/editor-scripting.md @@ -0,0 +1,110 @@ +# Running C# for Web optimization + +Links in this file resolve to the skill directory's `references/` folder, the folder this file is in, so `../scripts/` is the skill's `scripts/` folder. Project paths in code spans are relative to the user's project. + +## Contents + +- [Passing C# to `script eval`](#passing-c-to-script-eval) +- [Reading the settings this skill audits](#reading-the-settings-this-skill-audits) +- [Applying the settings](#applying-the-settings) +- [Verify from disk, not from the objects you just wrote](#verify-from-disk-not-from-the-objects-you-just-wrote) + +## Passing C# to `script eval` + +`script eval` compiles a **statement block, not a file**, so write the code without `using` directives and +with fully qualified types. If the code doesn't compile, look up the error here: + +| Error | Cause | Fix | +| --- | --- | --- | +| `CS0210` | A `using` directive, such as `using UnityEditor;`, which the compiler reads as a resource-disposal statement | Remove the directive and qualify the types | +| `CS0246` | An unqualified type, such as `PlayerSettings` | Use the full name, such as `UnityEditor.PlayerSettings` | +| `CS0104` | A bare `Object`, which is ambiguous with `object` | Use `UnityEngine.Object` | + +## Reading the settings this skill audits + +One call returns the whole Pre-Flight picture. Verified against Unity 6000.5.7f1: + +```csharp +var target = UnityEditor.Build.NamedBuildTarget.WebGL; +var w = new System.Collections.Generic.List<string>(); +w.Add($"activeBuildTarget={UnityEditor.EditorUserBuildSettings.activeBuildTarget}"); +w.Add($"compressionFormat={UnityEditor.PlayerSettings.WebGL.compressionFormat}"); +w.Add($"decompressionFallback={UnityEditor.PlayerSettings.WebGL.decompressionFallback}"); +w.Add($"stripEngineCode={UnityEditor.PlayerSettings.stripEngineCode}"); +w.Add($"managedStrippingLevel={UnityEditor.PlayerSettings.GetManagedStrippingLevel(target)}"); +w.Add($"il2cppCodeGeneration={UnityEditor.PlayerSettings.GetIl2CppCodeGeneration(target)}"); +w.Add($"apiCompatibilityLevel={UnityEditor.PlayerSettings.GetApiCompatibilityLevel(target)}"); +w.Add($"exceptionSupport={UnityEditor.PlayerSettings.WebGL.exceptionSupport}"); +w.Add($"debugSymbolMode={UnityEditor.PlayerSettings.WebGL.debugSymbolMode}"); +w.Add($"dataCaching={UnityEditor.PlayerSettings.WebGL.dataCaching}"); +w.Add($"wasm2023={UnityEditor.PlayerSettings.WebGL.wasm2023}"); +w.Add($"initialMemorySize={UnityEditor.PlayerSettings.WebGL.initialMemorySize}"); +w.Add($"maximumMemorySize={UnityEditor.PlayerSettings.WebGL.maximumMemorySize}"); +w.Add($"memoryGrowthMode={UnityEditor.PlayerSettings.WebGL.memoryGrowthMode}"); +w.Add($"targetFrameRate={UnityEngine.Application.targetFrameRate}"); +w.Add($"vSyncCount={UnityEngine.QualitySettings.vSyncCount}"); +return string.Join("\n", w); +``` + +**Three API names to get right**, because the obvious spellings do not exist and fail to compile: + +| Setting | Correct form | Does NOT exist | +|---|---|---| +| Managed stripping level | `PlayerSettings.GetManagedStrippingLevel(NamedBuildTarget.WebGL)` | `PlayerSettings.managedStrippingLevel` | +| Wasm code optimization | `UnityEditor.WebGL.UserBuildSettings.codeOptimization` | `PlayerSettings.WebGL.codeOptimization`, `PlayerSettings.WebGL.optimizationLevel` | +| IL2CPP code generation | `PlayerSettings.GetIl2CppCodeGeneration(NamedBuildTarget.WebGL)` | a bare property | + +`UserBuildSettings` lives in the WebGL build-support module, so it only resolves when that module is +installed. Read it in a separate call from the rest, and treat a resolution failure as "the Web +module isn't installed" rather than as a bad snippet. + +**`codeOptimization` is the one setting here that does not live in the project file.** It persists to +`Library/EditorUserBuildSettings.asset`, and `Library/` is gitignored by every standard Unity +`.gitignore`, so this value is per-machine and does not travel: teammates and CI do not inherit it. +Two consequences. Read it back through the API and do not look for it in +`ProjectSettings/ProjectSettings.asset` — it is absent there even on a successful apply, so its +absence is not a failure. And if the release build runs in CI, apply it there as a build step rather +than assuming the repository carries it. + +## Applying the settings + +Most of the writes in this skill are a single batch, and +[scripts/WebOptimizer.cs](../scripts/WebOptimizer.cs) already is that batch. It declares a class +with a `[MenuItem]`, so it is a **project file, not `script eval` input** — a class declaration cannot be +flattened into a statement block. Save it under `Assets/Editor/`, let Unity compile, then invoke it +in one line: + +```csharp +UnityEditor.EditorApplication.ExecuteMenuItem("Tools/Apply Web Release Settings"); +``` + +Keep its `using` directives; they are correct in a file. For one-off changes — a single quality +level, a frame-rate flip — an inline `script eval` statement is fine. + +## Verify from disk, not from the objects you just wrote + +**Applying a setting and reading it back in the same session proves nothing.** Player Settings are +in-memory objects until something saves them, so every read-back returns the value you just +assigned whether or not it ever reached +`ProjectSettings/ProjectSettings.asset`. A run that skips the save reports success, and when the +Editor session ends the whole change is gone. This was observed, not theorised: a run applied +everything, read back Brotli / High / None, said it was done, and the file on disk never changed. + +So after any write: + +1. **Save.** `UnityEditor.AssetDatabase.SaveAssets()`. `WebOptimizer.cs` now does this itself; an + inline `script eval` write has to do it explicitly. +2. **Read the values back and report them.** Not "applied successfully" but the actual values, so the + user can see what is stored. `WebOptimizer.cs` logs all nine. +3. **For anything per-build-target, name the target you read.** Several of these settings exist once + per target, so a value can be correct for one target and unset for the one being built. + +The same trap exists on the file-editing route in reverse: a hand-edited +`ProjectSettings.asset` reads back fine while the running Editor and the build still use the old +value. Verifying after a save and a reimport is what catches both. + +**Do not try to reproduce this in batch mode.** A batch Editor invoked with `-quit` saves settings on +exit, so an unsaved write persists anyway and the run looks correct. Both a saving and a non-saving +version of the script pass under `-quit`. The bug only appears in a live Editor session, which is +where it was found. Concluding from a green batch run that the save is unnecessary is the wrong +conclusion from a test that cannot see the defect. diff --git a/skills/using-unity/references/optimize-web/references/optimization-areas.md b/skills/using-unity/references/optimize-web/references/optimization-areas.md new file mode 100644 index 0000000..bbaf034 --- /dev/null +++ b/skills/using-unity/references/optimize-web/references/optimization-areas.md @@ -0,0 +1,203 @@ +# Web build optimization areas + +Release recommendations for each area of a Unity Web build. Read the matching docs page from the skill's topic map before you apply a value. + +Links in this file resolve to the skill directory's `references/` folder, the folder this file is in, so `../scripts/` is the skill's `scripts/` folder. Project paths in code spans are relative to the user's project. + +## Contents + +- [Player Settings audit](#player-settings-audit) +- [Compression and server configuration](#compression-and-server-configuration) +- [Exception handling](#exception-handling) +- [Remove unused resources](#remove-unused-resources) +- [Quality settings for Web](#quality-settings-for-web) +- [Frame rate on Web](#frame-rate-on-web) +- [KTX / Basis Universal textures](#ktx--basis-universal-textures) +- [Streaming on Web](#streaming-on-web) +- [Profiling Web builds](#profiling-web-builds) +- [Web memory directives](#web-memory-directives) +- [iOS Safari memory limits](#ios-safari-memory-limits) +- [Video and audio on Web](#video-and-audio-on-web) +- [Canvas and DPI](#canvas-and-dpi) + +## Player Settings audit + +Verify and set these values through `script eval`: + +| Setting | Release recommendation | +|---|---| +| **Compression Format** | **Brotli** (HTTPS hosting); Gzip for HTTP | +| **Decompression Fallback** | **Off** when server is correctly configured | +| **Strip Engine Code** | **On** | +| **Managed Stripping Level** | **High** (release) / Medium (dev) | +| **Code Optimization** | **Disk Size with LTO** (release) / Build Times (dev) | +| **WebAssembly Language Features** | **2023** if browser baseline allows | +| **Enable Exceptions** | **None** (smallest); Explicitly Thrown Only if `try/catch` required | +| **Initial Memory Size** | Tune to peak estimate; too small causes expensive growth | +| **Memory Growth Mode** | **Geometric** | +| **API Compatibility Level** | **.NET Standard 2.1** — smaller than .NET Framework | +| **IL2CPP Code Generation** | **Optimize Size** — smaller Wasm at slight runtime cost | +| **Debug Symbols** | **Off** for release; on for development builds only | +| **Data Caching** | **On** — caches asset data in browser IndexedDB for faster repeat loads | +| **Strip Unused Mesh Components** | **On** — removes unused vertex attributes | +| **Maximum Memory Size** | **2048 MB** default; up to 4096 for complex 3D (Firefox and Chrome < 119 have issues above 2048) | +| **vSyncCount** | 0 (browser handles pacing) | +| **targetFrameRate** | -1 (use `requestAnimationFrame`) | + +## Compression and server configuration + +| Compression | Use when | Notes | +|---|---|---| +| **Brotli** | HTTPS or localhost | Best ratio; browsers accept only over secure contexts | +| **Gzip** | HTTP delivery, legacy CDNs | Universal | +| **None** | Local dev / file:// | Largest payload; do not ship | + +Configure the server to: +- Serve `.br` files with `Content-Encoding: br`. +- Serve `.gz` files with `Content-Encoding: gzip`. +- Set `Content-Type: application/wasm` for `.wasm`, `application/javascript` for `.js`. +- Enable HTTP/2 or HTTP/3 to parallelize chunk fetches. + +If the host cannot inject `Content-Encoding`: set **Decompression Fallback = On** as a fallback only — it adds ~150 KB JS and slows startup. + +## Exception handling + +| Setting | Build size | Use | +|---|---|---| +| **None** | Smallest | Release builds where uncaught exceptions are acceptable | +| **Explicitly Thrown Only** | Modest | Default for projects that catch exceptions | +| **Full** | Largest, slowest | Rarely needed; avoid for release | + +Wasm 2023 introduces a cheaper exception model; switching from Explicitly Thrown Only (legacy) to Wasm exceptions reduces both size and cost when browser targets support it. + +## Remove unused resources + +Three categories to audit for build size reduction: + +**1. Unused packages** — Check `Packages/manifest.json` and the Package Manager **In Project** and **Built-in** views. Remove or disable packages the project does not use. The Input System package is a significant size contributor if unused. + +**2. Shader stripping** — Configure in `Edit > Project Settings > Graphics`: + +| Setting | Recommendation | +|---|---| +| **Lightmap Modes** | Automatic (strips unused lightmap shader variants) | +| **Fog Modes** | Automatic (strips unused fog shader variants) | +| **Instancing Variants** | Strip Unused | +| **Batch Renderer Group Variants** | Strip All (if BRGs are not used) | +| **Always Included Shaders** | Audit and remove any shaders the project does not reference | + +Test after stripping — make sure you didn't remove any referenced shaders. + +**3. Web Stripping Tool** (`com.unity.web.stripping-tool`) — Analyzes the WebAssembly binary and identifies unused Unity engine submodules (e.g. 3D graphics in a 2D-only game). Install via Package Manager, profile the build, then configure which submodules to exclude. Can yield substantial size reductions beyond what Managed Stripping Level achieves alone. + +## Quality settings for Web + +Lower quality levels reduce load time and improve runtime performance. Set via `Edit > Project Settings > Quality`: + +- Use **Very Low** or **Low** as the default Web quality level. +- Set it with `script eval`: `UnityEngine.QualitySettings.SetQualityLevel(0, true);` where 0 = Very Low. +- Consider creating a Web-specific quality level that disables features unnecessary in-browser (real-time shadows, post-processing effects, high particle counts). + +## Frame rate on Web + +- Set it with `script eval`: `UnityEngine.Application.targetFrameRate = -1;` — let the browser use `requestAnimationFrame`. +- Note: **Safari caps at 60 fps** in WebGL; high-refresh targets do not apply. +- Use `OnDemandRendering.renderFrameInterval` to drop to 5–10 fps on static/idle screens to save battery. + +## KTX / Basis Universal textures + +KTX2 with Basis Universal supercompression ships a single texture file that transcodes at load time to the optimal GPU format for the browser's device (BC7 on desktop, ASTC on mobile, ETC2 on older Android). This avoids shipping separate texture variants for each GPU family — critical for Web where the target hardware is unknown. + +| Topic | Guidance | +|---|---| +| **Package** | Install `com.unity.cloud.ktx` (KtxUnity) via Package Manager | +| **When to use** | Runtime-loaded textures via Addressables or asset bundles served to unknown GPU targets | +| **When NOT to use** | Textures baked into the player build — Unity already selects the correct format at build time | +| **Supercompression** | Use **ETC1S** for smallest size (lossy, good for diffuse/albedo); **UASTC** for higher quality (near-lossless, better for normals/UI) | +| **Encoding** | Encode offline with `toktx` or `basisu` CLI; do not encode at runtime | +| **Linear data** | Set `--assign_oetf linear` when encoding normal maps, masks, or data textures to avoid incorrect sRGB conversion | +| **Mip maps** | Generate mips at encode time (`--genmipmap`) — browser-side mip generation is expensive | +| **Loading** | Use `KtxTexture.LoadFromStreamingAssets` or load bytes via UnityWebRequest and call `KtxTexture.LoadFromBytes` | +| **Memory** | Transcoded textures are standard GPU textures; memory cost equals the target format, not the KTX2 file size | +| **Orientation** | Always include `--lower_left_maps_to_s0t0` to match Unity's UV convention | + +**`toktx` CLI examples:** See [scripts/toktx-examples.sh](../scripts/toktx-examples.sh) for commands covering albedo (ETC1S), normals/detail (UASTC), ICC profile errors, and linear data. + +## Streaming on Web + +- Use Addressables with **remote groups** hosted on a CDN with Brotli / Gzip. +- Avoid bundling the entire game into the initial download; stream levels on demand. +- Target < 30 MB initial download for "instant play"; level data follows. +- For streamed textures targeting mixed GPU hardware, prefer KTX2 bundles over per-platform variants — one bundle serves all browsers. + +## Profiling Web builds + +| Tool | Use | Notes | +|---|---|---| +| **Chrome DevTools > Performance** | CPU flamegraph; main-thread analysis | Default first stop for WebGL hitches; inspect Wasm call stacks | +| **Chrome DevTools > Memory** | Heap snapshot; allocation timeline | Find JS/Wasm memory leaks; compare snapshots before/after scene load | +| **Firefox Profiler** | Cross-platform; shareable URLs; native + Wasm view | Better Wasm symbolication than Chrome in some cases; shareable profile URLs for team review | +| **Safari Web Inspector** | iOS Safari and macOS Safari debugging | Required for Safari-specific issues; WebGL/Wasm runtime differs from Chromium | +| **Unity Profiler over WebSocket** | Connect to a development build; standard markers | Use for Unity-side markers (GC, rendering, scripts); does not capture browser-side overhead | + +**Symptom → tool quick reference:** + +| Symptom | First-line tool | Second-line tool | +|---|---|---| +| WebGL hitch / stutter | Chrome DevTools > Performance | Firefox Profiler | +| Memory climbing over time | Chrome DevTools > Memory | Unity Memory Profiler (WebSocket) | +| Slow initial load | Chrome DevTools > Network | Build Report Inspector | +| Safari-only rendering issue | Safari Web Inspector | Compare with Chrome DevTools | + +**Embedding profiling symbols** — browser profilers show mangled Wasm function names by default. To get readable C# method names in Chrome/Firefox flamegraphs, either enable `Player Settings > Publishing > Debug Symbols` for dev builds, or add a build processor: + +```csharp +using UnityEditor; +using UnityEditor.Build; +using UnityEditor.Build.Reporting; + +public class WebProfilingBuildProcessor : IPreprocessBuildWithReport +{ + public int callbackOrder => 0; + public void OnPreprocessBuild(BuildReport report) + { + PlayerSettings.SetAdditionalIl2CppArgs("--compiler-flags=--profiling-funcs"); + } +} +``` + +**Emscripten built-in profilers** — enable one at a time via `PlayerSettings.WebGL.emscriptenArgs`: + +| Flag | What it shows | +|---|---| +| `--cpuprofiler` | CPU profiler overlay in browser | +| `--memoryprofiler` | Visual memory map (white=allocated unused, pink=stack, blue=dynamic, green=fragmented) | +| `--threadprofiler` | Thread activity profiler | + +**GPU debugging** — No Frame Debugger support on Web. Use [Spector.js](https://spector.babylonjs.com/) as a browser-based alternative — it captures draw calls and WebGL state. + +**Firefox `about:memory`** — type `about:memory` as a URL in Firefox, click Measure to see per-tab breakdown: WASM code size, WASM heap, .data file, web audio. Watch for WASM heap > 300 MB (crash risk, especially on iOS Safari). + +Editor Play Mode does not represent browser runtime; always measure in browser. Chrome and Safari GC and JIT behavior differ — test both. + +## Web memory directives + +- Disable **Read/Write Enabled** on textures and meshes — it duplicates data into the WASM heap. +- Reduce `.data` file size by moving assets to Addressables or AssetBundles. +- Use compressed texture formats (KTX2/Basis) to reduce both download and decoded memory cost. + +## iOS Safari memory limits + +- **iOS < 18:** WebContent process limit ~1.5 GB. WASM memory (Gigacage) capped at 2 GB. Typed arrays share this pool. On iPhone X (iOS 16) heap growth caps at ~512 MB, but setting Initial Memory Size to 512 MB–1.5 GB upfront works. +- **iOS 18+:** Limits largely lifted; iPhone 11 can allocate ~4 GB. +- On iOS, set **Initial Memory Size** to the target peak rather than relying on growth — Safari handles large upfront allocations better than incremental growth. +- WASM heap > 300 MB risks crashes on older iOS; target < 200 MB for broad compatibility. + +## Video and audio on Web + +- **Video:** Playback only works from a URL (server with CORS enabled) or from StreamingAssets. On iOS the server must support HTTP range requests for streaming. Use browser-compatible formats (MP4/H.264). +- **Audio:** AudioEffects (mixer effects) require compute shaders — **not available on WebGL**. Mixers and MixerGroups work for volume control only. Set audio to **Mono** to improve loading. If `about:memory` shows web audio > 100 MB, audio is likely uncompressed — switch to Vorbis. + +## Canvas and DPI + +If the canvas is scaled up it takes the new resolution. Use `devicePixelRatio` in the web template to offset DPI scaling and avoid rendering at unnecessarily high resolution. diff --git a/skills/using-unity/references/optimize-web/references/troubleshooting.md b/skills/using-unity/references/optimize-web/references/troubleshooting.md new file mode 100644 index 0000000..53fbab6 --- /dev/null +++ b/skills/using-unity/references/optimize-web/references/troubleshooting.md @@ -0,0 +1,55 @@ +# Web build troubleshooting + +## Contents + +- [Build still large after enabling Strip Engine Code](#build-still-large-after-enabling-strip-engine-code) +- [Brotli not working — Decompression Fallback required](#brotli-not-working--decompression-fallback-required) +- [Stutter in Safari but not Chrome](#stutter-in-safari-but-not-chrome) +- [Memory growth slow path triggered](#memory-growth-slow-path-triggered) +- [Frame rate set to 60 but browser runs erratically](#frame-rate-set-to-60-but-browser-runs-erratically) +- [Firefox cache rejecting large files](#firefox-cache-rejecting-large-files) +- [Local dev server setup](#local-dev-server-setup) + +## Build still large after enabling Strip Engine Code + +1. Is **Managed Stripping Level** set to Medium or Low? → Set to High for release. +2. Are plug-ins using reflection to access engine modules that would otherwise be stripped? → Add a `link.xml` to preserve needed symbols. +3. Is **Exceptions** set to Full? → Full adds the largest code overhead; switch to None or Explicitly Thrown Only. + +## Brotli not working — Decompression Fallback required + +1. Is the server sending `Content-Encoding: br`? → Without this header the browser won't decompress; the fallback JS decompressor is then needed. +2. Is the build hosted over HTTP (not HTTPS)? → Brotli requires a secure context; degrade to Gzip for HTTP hosting. + +## Stutter in Safari but not Chrome + +1. Does the project set `Application.targetFrameRate = 60`? → On Safari WebGL this conflicts with browser pacing; set to `-1`. +2. Are there shaders that behave differently on Safari's WebGL implementation? → Test on device; Safari's WebGL/Wasm runtime differs from Chromium — some GLSL constructs are handled differently. + +## Memory growth slow path triggered + +1. Is **Initial Memory Size** too small for the project's peak? → Wasm memory growth requires a full buffer copy; set Initial Memory Size to a realistic peak estimate. +2. Is **Memory Growth Mode** set to Linear? → Switch to **Geometric** for saner growth curve. + +## Frame rate set to 60 but browser runs erratically + +1. Is `Application.targetFrameRate = 60` set in code? → On Web this conflicts with `requestAnimationFrame` browser pacing. Set to `-1`. +2. Is `vSyncCount` non-zero? → Set to 0; the browser handles pacing. + +## Firefox cache rejecting large files + +Firefox limits individual cache entries via `browser.cache.disk.max_entry_size`. If the build exceeds this (default ~50 MB), assets won't cache. Solution: use Addressables to split into bundles < 51 MB, or instruct users to increase the setting in `about:config`. + +## Local dev server setup + +For testing builds locally with proper MIME types: + +```bash +# Python (HTTP) +python -m http.server 55553 -d path/to/build + +# Node.js (install serve-handler) +npx serve path/to/build -l 3001 +``` + +For Brotli testing, use HTTPS — Brotli requires a secure context. Generate a self-signed cert with OpenSSL for local testing. diff --git a/skills/using-unity/references/audio-setup-mixers/SECURITY.md b/skills/using-unity/references/route-audio-to-mixer-groups/SECURITY.md similarity index 96% rename from skills/using-unity/references/audio-setup-mixers/SECURITY.md rename to skills/using-unity/references/route-audio-to-mixer-groups/SECURITY.md index 7ca3820..dd59c2d 100644 --- a/skills/using-unity/references/audio-setup-mixers/SECURITY.md +++ b/skills/using-unity/references/route-audio-to-mixer-groups/SECURITY.md @@ -1,4 +1,4 @@ -# Security notes: audio-setup-mixers +# Security notes: route-audio-to-mixer-groups This skill has the agent run C# inside the user's open Unity Editor through `unity command script eval`. Automated skill scanners flag that as a powerful capability. It is intentional, and it is limited by the safeguards below. diff --git a/skills/using-unity/references/audio-setup-mixers/references/api.md b/skills/using-unity/references/route-audio-to-mixer-groups/references/api.md similarity index 95% rename from skills/using-unity/references/audio-setup-mixers/references/api.md rename to skills/using-unity/references/route-audio-to-mixer-groups/references/api.md index c2cb094..986b859 100644 --- a/skills/using-unity/references/audio-setup-mixers/references/api.md +++ b/skills/using-unity/references/route-audio-to-mixer-groups/references/api.md @@ -1,3 +1,11 @@ +## Contents + +- What this skill does and does not automate +- Inventory the project's mixers and their groups +- Read what the scene's Audio Sources are currently routed to +- Assign groups to Audio Sources +- Asking the user to add a group + ## What this skill does and does not automate Every `AudioMixer` in the Editor is really an `AudioMixerController`, and every `AudioMixerGroup` is @@ -27,7 +35,7 @@ to add any missing groups (two clicks in a window they already have open), and t routing itself. The tedious part — walking dozens of Audio Sources and classifying them — is the part that was worth automating anyway. -All snippets below are written for `unity command script eval --caller plugin --skill audio-setup-mixers --code '<snippet>'`: fully qualified, no +All snippets below are written for `unity command script eval --caller plugin --skill route-audio-to-mixer-groups --code '<snippet>'`: fully qualified, no `using` directives, returning their result rather than logging it. ## Inventory the project's mixers and their groups @@ -69,7 +77,7 @@ foreach (var source in sources) { var group = source.outputAudioMixerGroup; rows.Add($"{source.gameObject.name}: clip={(source.clip != null ? source.clip.name : "<none>")}, " - + $"group={(group != null ? group.name : "<none — routes to Master>")}"); + + $"group={(group != null ? group.name : "<none — bypasses the mixer>")}"); } return rows.Count == 0 ? "no Audio Sources in the open scene" : string.Join("\n", rows); ``` diff --git a/skills/using-unity/references/route-audio-to-mixer-groups/route-audio-to-mixer-groups.md b/skills/using-unity/references/route-audio-to-mixer-groups/route-audio-to-mixer-groups.md new file mode 100644 index 0000000..e9d459d --- /dev/null +++ b/skills/using-unity/references/route-audio-to-mixer-groups/route-audio-to-mixer-groups.md @@ -0,0 +1,213 @@ +--- +name: route-audio-to-mixer-groups +description: Routes Audio Sources into existing Audio Mixer Groups, classifying each source by what it plays. Use when the user asks about cleaning up mixer assignments, routing audio through a mixer, or which group a sound belongs in. +--- +# Route Audio to Mixer Groups + +## Important + +- Use the unity cli (`unity command --format json`) and the `unity-cli` and `unity-pipeline` skills for each step. +- Before making changes, establish a baseline of the current behavior so you can tell whether a later result is actually caused by your change. +- Create a restore point you can roll back to if your changes fail. +- Do only what's asked. Don't change unrelated assets or files. +- Avoid long explanations. +- Never leave verification code in the user's script. Never build logging or detection they didn't ask for. See [Final step](#final-step). + +## Full topic map + +Before you go forward with a workflow or diagnosis: + +1. Open and read the [documentation page(s)](#full-topic-map) that cover the specific subject related to what you intend to do or fix and check if you've missed anything. +2. Name the file(s) you read in your response. + +This is because your training knowledge about Unity might be out of date, incorrect, or for the wrong Unity version. + +If the Editor install folder has a `Data/Documentation` folder (eg `...Unity/Hub/Editor/6000.6.0b2/Editor/Data/Documentation`), read the html files from `<editor-install>/Editor/Data/Documentation/en/Manual` and `<editor-install>/Editor/Data/Documentation/en/ScriptReference`, using the local file names below. + +Otherwise read the online pages listed below under `https://docs.unity.com/en-us/engine/<VERSION>/`, as markdown. + +Prefer fetching the page directly (for example `WebFetch`) over searching (for example `WebSearch`) — faster and lands on the exact reference. Only fetch what you need, and only search if you don't have the exact URL. Replace `<VERSION>` with the following before fetching: + +- **docs.unity3d.com**: The Unity version, eg `6000.3` +- **Engine on docs.unity.com**: The Unity version, eg `6000.3` + +Find the Unity version in `ProjectSettings/ProjectVersion.txt`, and use only its first two parts (`6000.3.2f1` becomes `6000.3`). + +Manual pages: local file in `en/Manual`, then online page under `https://docs.unity.com/en-us/engine/<VERSION>/manual/`: + +- `AudioMixerOverview.html` — `audio/mixer/overview.md`: what an Audio Mixer and its groups do. +- `AudioMixerSpecifics.html` — `audio/mixer/specifics.md`: creating a mixer and adding groups in the Audio Mixer window. +- `class-AudioSource.html` — `audio/reference/class-audio-source.md`: Audio Source properties, including Output. + +Script Reference pages: local file in `en/ScriptReference`, then online page under `https://docs.unity.com/en-us/engine/<VERSION>/script-reference/`: + +- `Audio.AudioMixer.FindMatchingGroups.html` — `unityengine/audio/audiomixer/findmatchinggroups.md`: listing a mixer's groups. +- `AudioSource-outputAudioMixerGroup.html` — `unityengine/audiosource/outputaudiomixergroup.md`: reading and setting an Audio Source's group. +- `AssetDatabase.FindAssets.html` — `unityeditor/assetdatabase/findassets.md`: finding mixer assets, and its overloads. + +Routing an Audio Source to a mixer group is a scene edit that only a running Editor can +make, so this skill needs a live Editor it can execute C# in. Step 0 establishes that +before anything else. + +**Automate the routing; hand group creation to the user.** Inspect mixers and route Audio +Sources into groups yourself, because that is all public Unity API. Don't create a mixer or +a group yourself, because that has no public API; it exists only on types Unity does not +commit to keeping stable. Inventory what exists, propose the routing, ask the user to add +any missing group in the Audio Mixer window, then do all the routing yourself. + +That is a deliberate limit, not a gap to work around. Do not reach for reflection to +create groups, and do not hand-edit a `.mixer` file — mixer structure is not safely +authorable blind. + +### API reference + +The API is `UnityEngine.Audio.AudioMixer`, `UnityEngine.AudioSource` and `UnityEditor.AssetDatabase`, part of the Unity Engine. It is versioned by Unity version, so check the project's Unity version before relying on a specific class or method. + +1. Use the `unity-cli` skill to check the project's Unity version. +2. If the Editor install folder has a `Data/Documentation` folder (e.g. `<editor-install>/Editor/Data/Documentation`), grep the html files in the `en/ScriptReference` folder inside, and skip the remaining steps. +3. Otherwise, fetch and cache `https://docs.unity3d.com/<VERSION>/Documentation/ScriptReference/xrefmap.yml` (replace `<VERSION>` with the Unity version, e.g. `6000.3`). This file lists every public API member's fully qualified name as a `uid` (e.g. `uid: 'UnityEngine.Audio.AudioMixer.FindMatchingGroups(System.String)'`). +4. Grep the yml file locally for a class or method instead of refetching per lookup. The file is large (about 6 MB), so don't read the whole file. +5. Convert the `uid` to a markdown page: remove the parameters in brackets, lowercase it, replace `.` with `/`, and add `.md`. Then fetch `https://docs.unity.com/en-us/engine/<VERSION>/script-reference/<converted uid>`. For example, `UnityEngine.Audio.AudioMixer.FindMatchingGroups(System.String)` => `https://docs.unity.com/en-us/engine/6000.3/script-reference/unityengine/audio/audiomixer/findmatchinggroups.md`. All overloads are on the same page. + - Constructors use `ctor` (e.g. `unityengine/vector3/ctor.md`), and indexers use `item` (e.g. `unityengine/vector3/item.md`). + - For operators, fetch the class page (e.g. `unityengine/vector3.md`) and follow its link. + - Links inside the pages start with `/engine/`. Add `https://docs.unity.com/en-us` before them. + - If the page doesn't exist for that Unity version, use the `href` in the `xrefmap.yml` entry instead (e.g. `href: 'Audio.AudioMixer.FindMatchingGroups.html'` => `https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Audio.AudioMixer.FindMatchingGroups.html`). + +Always use the docs for the project's Unity version rather than relying on training knowledge, since APIs are frequently marked obsolete between versions. + +## Step 0: Confirm you can run C# in the Editor + +Every C# step below runs inside a live Editor through the Unity CLI. **The `unity-cli` skill +owns getting you there** — installing the CLI, confirming a connected Editor, adding the +project's `com.unity.pipeline` package, telling a genuinely absent Editor apart from one +stuck in Safe Mode, and discovering the Editor's command catalog. Follow it first; don't +re-derive any of it here. + +Two things it can't know for you: + +- **You need `script eval` in particular**, not just a reachable Editor. Confirm it appears in the + catalog. Its presence depends on the Pipeline package version, not on the CLI, so a + healthy install can still lack it — if it's missing, say so and stop. +- **Do not fall back to editing `.mixer` files by hand.** Mixer routing is not safely + authorable blind, so an unreachable Editor is a stop, not a cue to improvise. + +Once `script eval` is available, that is how each C# step below runs. + +Run C# through the connected Editor with the `script eval` command. Discover its parameter shape +from `unity command --format json` rather than assuming one — the inline form is +`unity command script eval --caller plugin --skill route-audio-to-mixer-groups --code '<snippet>'`, and some Pipeline versions also register +`script eval_file` for running a snippet from a file. **Check the catalog before reaching for +`script eval_file`; it is frequently absent.** `script eval`'s default timeout depends on the Pipeline version, so read it from the command's schema (`unity command --detail full --format json`) and pass `--timeout <seconds>` for a slow call. + +### Passing C# to `script eval` + +`script eval` compiles a **statement block, not a file**, so write no `using` directives and fully +qualify every type. If `script eval` returns one of these compile errors, apply the fix and re-run: + +| Error | Cause | Fix | +|---|---|---| +| `CS0210` | A `using` directive, which the compiler reads as a resource-disposal statement | Remove every `using` directive | +| `CS0246` / `CS0103` | A bare type name, such as `AssetDatabase` or `AudioMixer` | Fully qualify it, for example `UnityEditor.AssetDatabase` | +| `CS0104` | A bare `Object`, which is ambiguous with `object` | Write `UnityEngine.Object` | + +Where a snippet below is written as a file — with usings, for readability, or because it is +meant to be saved into the project — qualify the types before passing it to `script eval`. + +## Step 1: Pre-flight +If the user hasn't explicitly asked for Audio Mixers, confirm that they want to proceed with setting them up, because routing changes the output of every Audio Source in the scene. Otherwise go straight to the inventory. + +Then inventory what already exists with the mixer-inventory snippet in +[references/api.md](references/api.md), run through the Editor as described in Step 0. That gives +you every mixer in the project and the group names in each. + +It returns a flat list of groups, not the parent/child tree. That is enough to route into, and it +is all the public API exposes. If the hierarchy matters for the conversation, ask the user to look +at the Audio Mixer window and describe it — don't reach for the non-public tree API to find out. + +**If the project has no mixer at all,** say so and stop rather than improvising one: creating a +mixer has no public API. Ask the user to create one (Window → Audio → Audio Mixer, then the **+** +next to Mixers), and pick up from here once it exists. + +## Step 2: Find scene references +1. List every Audio Source, its Audio Clip and its current group with the read-routing snippet in + [references/api.md](references/api.md). +2. Classify each source by its Audio Clip asset name into a sound category, preferring one that + already exists as a group, because the user's existing mix structure is the one to keep. + Examples for Audio Clip asset names: + - "FootStep4_Sound" -> Foley + - "Dialogue_Female_Scene4" -> Vox/Voice/Dialogue + - "GunShot" -> SFX + - "Menu_Theme_Variation" -> Music +3. If the clip name isn't descriptive, or the source has no Audio Clip (for example a script + supplies the audio at runtime), classify it by its GameObject name, then by the MonoBehaviours on + the same GameObject, because those are the next most reliable signs of what it plays. +4. If none of those make the category clear, propose an Uncategorized group for that source rather + than guessing, because a wrongly routed sound is harder for the user to spot than an unsorted one. + +## Step 3: Agree the group list, and get any missing groups created +Present the classification from Step 2 as a proposed routing — each Audio Source and the group you +intend to send it to — and revise it with the user. + +**WAIT for the user to respond before proceeding.** + +Prefer an existing group when it genuinely covers the category, even if you'd have named it +differently. But **don't collapse categories that a mixing engineer would keep apart** — Foley is a +subset of SFX, not another word for it, so a gunshot does not belong in a `Foley` group just because +one exists. When the existing groups only partly cover your categories, say which ones fit and which +need a new group, and let the user decide. + +For categories with no matching group, you cannot create the group — there is no public API for it. +Hand it over precisely, naming the mixer and the exact group names, as shown at the end of +[references/api.md](references/api.md). Then **re-run the inventory snippet to confirm the groups +exist and check their spelling** before routing. Don't assume the user did it, and don't assume +they spelled it the way you asked. + +## Step 4: Route the Audio Sources +With the group list settled and confirmed present, assign each Audio Source's output group using the +routing snippet in [references/api.md](references/api.md). It is public API throughout, and it wraps +the whole pass in a single undo step so the user can back all of it out at once. + +**Key the mapping on the identifier you classified by.** Step 2 reads the clip asset name first and +only falls back to the GameObject name, so the mapping accepts either — the two are different +identifiers and keying on the wrong one drops sources. + +Three things to report rather than assume: + +- **Any `NO SUCH GROUP` entries the snippet returns.** That means a group you expected is not in the + mixer — usually a spelling difference. Resolve it with the user, don't silently skip the source. +- **Any `NOT IN THE MAPPING` entries.** Those are Audio Sources your classification missed. Reporting + a successful routing while sources were quietly left unrouted is the worst outcome here, because it + reads as success. +- **The scene was modified, not the mixer asset.** Routing lives on the Audio Source, so it only + persists once the scene is saved. Tell the user, and save only with their agreement. + +**Volume, effects, and re-parenting are out of scope.** Those live on non-public API. If the user +asks for them, say the routing is done and point them at the Audio Mixer window for the mix itself. + +## Final step + +Do the following checks: + +1. Re-run the read-routing snippet in [references/api.md](references/api.md) and check every + routed Audio Source now reports its agreed group. If one doesn't, report it rather than re-running + the routing, because a mismatch usually means a misspelled group or two GameObjects sharing a name. +2. Check the project has zero console errors. Use `console status` for counts. +3. Stop there unless the user asked you to prove it works or you suspect a specific fault. +4. If you do enter Play mode, do it once only to chase a fault you already suspect. Read the world + through `script eval` rather than adding logging. Take no screenshots, because they take too much time. + +If a check fails, go back and reread the [docs pages](#full-topic-map) to find out what you missed. + +## Final report + +Report to the user, in order: + +1. **Routed**: each Audio Source and the group you routed it to. +2. **Not routed**: any `NOT IN THE MAPPING` sources, and why. +3. **Missing groups**: any `NO SUCH GROUP` entries, and the exact group names the user needs to create. +4. **Save the scene**: whether the scene still needs saving for the routing to persist. +5. **Side effects**: anything else you changed, and the undo step ("Route Audio Sources to mixer + groups") that reverts the whole routing pass. + +## References +See [references/api.md](references/api.md) \ No newline at end of file diff --git a/skills/using-unity/references/setup-vivox-voice-chat/SECURITY.md b/skills/using-unity/references/setup-vivox-voice-chat/SECURITY.md index d186da7..56db502 100644 --- a/skills/using-unity/references/setup-vivox-voice-chat/SECURITY.md +++ b/skills/using-unity/references/setup-vivox-voice-chat/SECURITY.md @@ -6,11 +6,10 @@ This skill can have the agent run C# in the user's live Unity Editor with `unity | Risk | Capability | Why it is accepted | |---|---|---| -| `SEC_POWER_CAP` | Runs C# in the user's live Editor through `unity command script eval` | It only reaches the Editor the user already has open, on their own machine, as that user, so it grants nothing they couldn't do themselves. The skill uses it to read state and `return` values, not to change the project. | +| `SEC_POWER_CAP` | Runs C# in the user's live Editor through `unity command script eval` | It only reaches the Editor the user already has open, on their own machine, as that user, so it grants nothing they couldn't do themselves. It also changes the project: it installs the Vivox package (`com.unity.services.vivox`) when it is missing. | ## Mitigations - **Only the user's own Editor.** The code runs in the Editor open on this machine. It can't reach another machine or another user's Editor. -- **Reads, not writes.** The skill uses `script eval` to read values it returns, instead of adding logging or detection code to the user's scripts. - **Nothing left behind.** The skill tells the agent never to leave verification code in the user's scripts, and to create a restore point before changes. -- **No remote code.** The skill fetches Vivox documentation to read it. Nothing downloaded from outside is executed. +- **No remote code.** Nothing downloaded from outside is executed. diff --git a/skills/using-unity/references/setup-vivox-voice-chat/setup-vivox-voice-chat.md b/skills/using-unity/references/setup-vivox-voice-chat/setup-vivox-voice-chat.md index 17d2ef7..f876904 100644 --- a/skills/using-unity/references/setup-vivox-voice-chat/setup-vivox-voice-chat.md +++ b/skills/using-unity/references/setup-vivox-voice-chat/setup-vivox-voice-chat.md @@ -176,7 +176,7 @@ After writing code that uses this package: Do the following checks: -1. Check the project has zero console errors. Use `console_status` for counts. +1. Check the project has zero console errors. Use `console status` for counts. 2. Stop there unless the user asked you to prove it works or you suspect a specific fault. 3. If you do enter Play mode, do it once only to chase a fault you already suspect. Read the world through `script eval` rather than adding logging. Take no screenshots as they take too much time. diff --git a/skills/using-unity/references/shader-graph-create-custom-node/SECURITY.md b/skills/using-unity/references/shader-graph-create-custom-node/SECURITY.md new file mode 100644 index 0000000..4e6934e --- /dev/null +++ b/skills/using-unity/references/shader-graph-create-custom-node/SECURITY.md @@ -0,0 +1,16 @@ +# Security notes: shader-graph-create-custom-node + +This skill has the agent read state from the user's open Unity Editor through `unity command script eval` when it checks a suspected fault in Play mode after it writes a reflected HLSL function. Automated skill scanners flag running code in the Editor as a powerful capability. It is intentional, and it is limited by the safeguards below. + +## Accepted risks + +| Risk | Capability | Why it is accepted | +|---|---|---| +| `SEC_POWER_CAP` | Runs C# in the user's open Editor through `unity command script eval` | It only reaches the Editor the user already has open, on their own machine, as that user, so it grants nothing they couldn't do themselves. `script eval` sits behind the Pipeline capability gate. No code fetched from a remote source is run. | + +## Mitigations + +- **Only the user's own Editor.** `unity command script eval` talks to the Editor open on this machine. It can't reach another machine or another user's Editor. +- **Capability gate.** `script eval` is only available when the project's Pipeline package provides it. +- **No remote code.** The agent runs C# it writes itself to read Editor state. Nothing downloaded from outside is executed. +- **Read only, once.** The skill enters Play mode at most once, to chase a fault it already suspects, and reads state instead of adding logging or verification code to the user's scripts. It creates a restore point before it changes the project. diff --git a/skills/using-unity/references/shader-graph-create-custom-node/resources/all_hints.hlsl b/skills/using-unity/references/shader-graph-create-custom-node/references/all_hints.hlsl similarity index 100% rename from skills/using-unity/references/shader-graph-create-custom-node/resources/all_hints.hlsl rename to skills/using-unity/references/shader-graph-create-custom-node/references/all_hints.hlsl diff --git a/skills/using-unity/references/shader-graph-create-custom-node/shader-graph-create-custom-node.md b/skills/using-unity/references/shader-graph-create-custom-node/shader-graph-create-custom-node.md index 691ca95..f8124ff 100644 --- a/skills/using-unity/references/shader-graph-create-custom-node/shader-graph-create-custom-node.md +++ b/skills/using-unity/references/shader-graph-create-custom-node/shader-graph-create-custom-node.md @@ -1,25 +1,106 @@ --- name: shader-graph-create-custom-node -description: Generates custom Shader Graph nodes from HLSL code. Use when the user wants a new Shader Graph node or to make existing HLSL work as a reflected function node. +description: Generates custom Shader Graph nodes from HLSL code by reflection. Use when asked for a new Shader Graph node, or to make existing HLSL work as a reflected function node. required_packages: com.unity.shadergraph: ">=17.5.0" --- -# Generating a custom Shader Graph node +Help the user turn an HLSL function into a custom Shader Graph node by reflection. -## Step 1: Generate an HLSL function definition -- The function must be preceded by the preprocessor define `UNITY_EXPORT_REFLECTION` +## Important -## Step 2: Decorate with Shader Graph hint tags -- See `resources/all_hints.hlsl` for all valid hint tags and usage patterns -- C#-style documentation tags are supported outside of `funchints` or `paramhints` blocks -- Required function hints: +- Use the unity cli (`unity command --format json`) and the `unity-cli` and `unity-pipeline` skills for each step. +- Run C# with `unity command script eval --caller plugin --skill shader-graph-create-custom-node --code '<snippet>'`. Don't use `using` directives or unqualified types in the snippet. The compiler reads using `UnityEngine` and a bare AssetDatabase, Volume, or Object causes errors (CS0246 / CS0103 / CS0104). `return` what you want to read; it arrives at `data.result.result`. +- Create a restore point you can roll back to if your changes fail. +- Do only what's asked. Don't change unrelated assets or files. +- Never leave verification code in the user's script. Never build logging or detection they didn't ask for. See [Final step](#final-step). +- Avoid long explanations. + +## Step 1 + +Before you go forward with a workflow or diagnosis: + +1. Open and read the [documentation page(s)](#full-topic-map) that cover the specific subject related to what you intend to do or fix and check if you've missed anything. +2. Name the file(s) you read in your response. + +This is because your training knowledge about Unity might be out of date, incorrect, or for the wrong Unity version. + +## Full topic map + +The Shader Graph manual is package documentation, not part of the Unity Manual, so don't look for it in the Unity Editor's `Data/Documentation` folder. + +The docs pages are local markdown conversions of the Unity Manual, stored at `<project-folder>/Library/PackageCache/com.unity.shadergraph@*/`. Read only the .md files in that specific `PackageCache` subfolder. You must not look at non-.md files, or look outside at other Library or PackageCache folders, otherwise it takes too much time. The pages are in its `Documentation~` folder. If that folder has no `.md` files, use the online pages at `https://docs.unity3d.com/Packages/com.unity.shadergraph@<VERSION>/manual/` in the following list instead, because some package versions don't ship their docs. + +Prefer fetching the page directly (for example `WebFetch`) over searching (for example `WebSearch`) — faster and lands on the exact reference. Only fetch what you need, and only search if you don't have the exact URL. Replace `<VERSION>` with the following before fetching: + +- **docs.unity3d.com**: The Unity version, eg `6000.6` +- **Package on docs.unity3d.com**: The package version, eg `@6.6` or `@2.0`. Check the package version if unsure. +- **Engine on docs.unity.com**: The Unity version, eg `6000.3` +- **docs.unity.com**: The product version, eg `7000.0` + +Read the Shader Graph major.minor from `com.unity.shadergraph` in `Packages/packages-lock.json` (for example `17.5` from `17.5.0`), because the full version number gives a 404. + +- [Introduction to HLSL in Shader Graph](https://docs.unity3d.com/Packages/com.unity.shadergraph@<VERSION>/manual/Custom-nodes-hlsl-introduction.html) — local `Custom-nodes-hlsl-introduction.md`: Custom Function nodes compared with nodes reflected from HLSL. +- [Create a custom node by reflection from HLSL](https://docs.unity3d.com/Packages/com.unity.shadergraph@<VERSION>/manual/Custom-nodes-hlsl-create-node-by-reflection.html) — local `Custom-nodes-hlsl-create-node-by-reflection.md`: the include, `UNITY_EXPORT_REFLECTION`, and adding function and parameter hints. +- [Reflected function hints reference](https://docs.unity3d.com/Packages/com.unity.shadergraph@<VERSION>/manual/Custom-nodes-hlsl-reflection-hints-reference.html) — local `Custom-nodes-hlsl-reflection-hints-reference.md`: every `funchints` and `paramhints` tag and its values. +- [Reflected Function node](https://docs.unity3d.com/Packages/com.unity.shadergraph@<VERSION>/manual/Reflected-Function-Node.html) — local `Reflected-Function-Node.md`: the node Shader Graph creates from a reflected function. + +### API reference + +The API is `UnityEditor.ShaderGraph`, part of the `com.unity.shadergraph` package. It is versioned by package version, not Unity version (e.g. `@17.5`, `@17.6`), so check the project's installed package version before relying on a specific class or method. + +1. Use the `unity-cli` skill to check the installed package version. +2. Fetch and cache `https://docs.unity3d.com/Packages/com.unity.shadergraph@<VERSION>/xrefmap.yml` (replace `<VERSION>` with the installed package version, e.g. `17.5`). This file maps every public API member's fully qualified name to its docs page `href` (e.g. `href: api/UnityEditor.ShaderGraph.html` => `https://docs.unity3d.com/Packages/com.unity.shadergraph@<VERSION>/api/UnityEditor.ShaderGraph.html`). +3. Grep the yml file locally for a class or method instead of refetching per lookup. Don't read the whole file. + +Always fetch the version matching the installed package rather than relying on training knowledge, since APIs are frequently marked obsolete between major versions. + +## Procedure + +1. Get the Shader Graph version from `com.unity.shadergraph` in `Packages/packages-lock.json`. If you can't find it, assume Shader Graph 17.5, name the assumption in your report, and carry on. If there's no project at all, give the user the HLSL code and the file to save it in, and say that you didn't write the file. If the user gives no HLSL function and doesn't describe the node they want, ask for it. +2. Read the doc pages from the [Full topic map](#full-topic-map) that cover what you're about to do. If you can't reach the docs, carry on from this skill and say so in your report. +3. Follow [Step 2](#step-2-generate-an-hlsl-function-definition), [Step 3](#step-3-decorate-with-shader-graph-hint-tags) and [Step 4](#step-4-write-the-code-to-an-asset) in order. +4. Check the Console for HLSL compile errors from the `.hlsl` asset, and check that the node appears in the Shader Graph Create Node menu under its `sg:SearchCategory`. If it doesn't, compare the code with [references/all_hints.hlsl](references/all_hints.hlsl) and fix it. Then run the [Final step](#final-step). +5. Report back as described in [Final report](#final-report), including whether the Final step checks passed. + +## Step 2: Generate an HLSL function definition +- Precede the function with the preprocessor define `UNITY_EXPORT_REFLECTION` + +## Step 3: Decorate with Shader Graph hint tags +- Refer to [references/all_hints.hlsl](references/all_hints.hlsl) for all valid hint tags and usage patterns +- You can use C#-style documentation tags outside of `funchints` or `paramhints` blocks +- Add these required function hints: - `sg:ProviderKey` - `sg:SearchCategory` - `sg:SearchTerms` - `sg:DisplayName` -## Step 3: Write the code to an asset +## Step 4: Write the code to an asset - Search the project for a `ShaderInclude` asset (`.hlsl`) that already contains custom Shader Graph nodes - If a matching asset exists, show the user its current contents and ask for confirmation before appending the new code - If no matching asset exists, create a new `.hlsl` asset - Ensure the file begins with `#include "ShaderApiReflectionSupport.hlsl"` + +## Final step + +Do the following checks: + +1. Check the project has zero console errors. Use `console status` for counts. +2. Stop there unless the user asked you to prove it works or you suspect a specific fault. +3. If you do enter Play mode, do it once only to chase a fault you already suspect. Read the world through `script eval` rather than adding logging. Take no screenshots as they take too much time. + +If a check fails, go back and reread the [docs pages](#full-topic-map) to find out what you missed. + +## Final report + +Give the user a concise but not dense checklist of what you did and why, including any incidental side effects (for example, settings you toggled to test something, or temporary files you created). If the user needs to follow up with more steps or decisions, list them. For example: + +``` +I made the following changes: + +[✓] Added a reflected `BlendOverlay` function to `Assets/Shaders/CustomNodes.hlsl`. + +Follow these steps to use the node: + +1. Open a Shader Graph asset. +2. Open the Create Node menu and find **Blend Overlay** under **Custom/Blend**. +``` diff --git a/skills/using-unity/references/sprite-editor/references/api_reference.md b/skills/using-unity/references/sprite-editor/references/api_reference.md index 4df0181..b8cc2ad 100644 --- a/skills/using-unity/references/sprite-editor/references/api_reference.md +++ b/skills/using-unity/references/sprite-editor/references/api_reference.md @@ -1,5 +1,7 @@ # Unity Sprite Editor API Reference +Markdown links in this file are relative to this file. Any other relative path resolves to the skill directory, the parent of this `references` folder. + ## Table of Contents - [Core Interface: ISpriteEditorDataProvider](#core-interface-ispriteeditordataprovider) - [Properties](#properties) diff --git a/skills/using-unity/references/sprite-editor/references/background.md b/skills/using-unity/references/sprite-editor/references/background.md index 296dbf2..8819600 100644 --- a/skills/using-unity/references/sprite-editor/references/background.md +++ b/skills/using-unity/references/sprite-editor/references/background.md @@ -1,5 +1,7 @@ # Sprite Editor Background Information +Markdown links in this file are relative to this file. Any other relative path, such as `scripts/README.md`, resolves to the skill directory, the parent of this `references` folder. + ## Table of Contents - [Why Use ISpriteEditorDataProvider](#why-use-ispriteeditordataprovider) - [Original vs Imported Image Sizes](#original-vs-imported-image-sizes) diff --git a/skills/using-unity/references/sprite-editor/sprite-editor.md b/skills/using-unity/references/sprite-editor/sprite-editor.md index 2248636..f643c3b 100644 --- a/skills/using-unity/references/sprite-editor/sprite-editor.md +++ b/skills/using-unity/references/sprite-editor/sprite-editor.md @@ -1,11 +1,89 @@ --- name: sprite-editor -description: Edits Unity sprite rectangles, borders, pivots, outlines, and slicing by generating C# scripts. Use when the user works with sprite sheets or sprite slicing. -modes: [agent, ask] +description: Edits sprite rectangles, names, borders, pivots, outlines, and slicing in a texture's import data by generating C# Editor scripts. Use when asked to slice a sprite sheet or change sprite pivots, borders, or outlines by script. +required_packages: + com.unity.2d.sprite: ">=1.0.0" --- # Sprite Editor +Edit sprite metadata (rects, names, borders, pivots, outlines) through `ISpriteEditorDataProvider` in a connected Unity Editor. + +## Important + +- Use the unity cli (`unity command --format json`) and the `unity-cli` and `unity-pipeline` skills for each step. +- Don't use `using` directives or unqualified types in the `snippet` for `script eval`. The compiler reads using `UnityEngine` and a bare AssetDatabase, Volume, or Object causes errors (CS0246 / CS0103 / CS0104). `return` what you want to read; it arrives at `data.result.result`. +- Create a restore point you can roll back to if your changes fail. +- Do only what's asked. Don't change unrelated assets or files. +- Never leave verification code in the user's script. Never build logging or detection they didn't ask for. See [Final step](#final-step). +- Avoid long explanations. + +## Step 1 + +Before you go forward with a workflow or diagnosis: + +1. Open and read the [documentation page(s)](#full-topic-map) that cover the specific subject related to what you intend to do or fix and check if you've missed anything. +2. Name the file(s) you read in your response. + +This is because your training knowledge about Unity might be out of date, incorrect, or for the wrong Unity version. + +## Full topic map + +The Sprite Editor Data Provider API docs ship with the 2D Sprite package. The docs pages are local markdown conversions of the Unity Manual, stored at `<project-folder>/Library/PackageCache/com.unity.2d.sprite@*/`. Read only the .md files in that specific `PackageCache` subfolder. You must not look at non-.md files, or look outside at other Library or PackageCache folders, otherwise it takes too much time. If that folder has no `.md` files, fetch `https://docs.unity3d.com/Packages/com.unity.2d.sprite@<VERSION>/manual/DataProvider.html`, because that website has no `.md` variant. + +The Sprite Editor window pages are in the Unity Manual. Check the project's Unity version first, because the docs location depends on it: + +- **Unity 6000.0 and later**: If the Editor install folder has a `Data/Documentation` folder (eg `...Unity/Hub/Editor/6000.6.0b2/Editor/Data/Documentation`), read the html files from the `<editor-install>/Editor/Data/Documentation/en/Manual` folder. Otherwise the docs pages are online at `https://docs.unity.com/en-us/engine/<VERSION>/manual/`. +- **Earlier versions**: Read the same local folder if it exists. Otherwise fetch `https://docs.unity3d.com/<VERSION>/Documentation/Manual/SpriteEditor.html` and follow its links, because docs.unity.com has no pages for those versions and the file names differ. + +Prefer fetching the page directly (for example `WebFetch`) over searching (for example `WebSearch`) — faster and lands on the exact reference. Only fetch what you need, and only search if you don't have the exact URL. Replace `<VERSION>` with the following before fetching: + +- **docs.unity3d.com**: The Unity version, eg `6000.6` +- **Package on docs.unity3d.com**: The package version, eg `@6.6` or `@2.0`. Check the package version if unsure. +- **Engine on docs.unity.com**: The Unity version, eg `6000.3` +- **docs.unity.com**: The product version, eg `7000.0` + +Before fetching, check that `<VERSION>` is listed as a `## Version` heading in https://docs.unity.com/en-us/engine/llms.txt. If it isn't, use the docs.unity3d.com Manual instead. The two sites use different page names, so don't reuse the paths below. Instead, find each page by its title in `https://docs.unity3d.com/<VERSION>/Documentation/Manual/docdata/toc.js`, then fetch `https://docs.unity3d.com/<VERSION>/Documentation/Manual/<link>.html`, where `<link>` is the `link` value next to the title. + +For Engine pages, `<VERSION>` is the Unity major.minor from `ProjectSettings/ProjectVersion.txt`, for example `6000.0` from `6000.0.58f1`, because the full build number gives a 404. For the 2D Sprite package, `<VERSION>` is the `com.unity.2d.sprite` major.minor from `Packages/packages-lock.json`, for example `1.0`. + +- **Sprite Editor Data Provider API** — `Documentation~/DataProvider.md` in `PackageCache`: code examples for editing sprite data through the providers. +- [Cut out sprites from a texture](https://docs.unity.com/en-us/engine/<VERSION>/manual/unity2d/sprite/use-editor.md) — local `sprite/sprite-editor/use-editor.html`: slicing a texture into sprites in the Sprite Editor window. +- [Sprite Editor tab reference for the Sprite Editor window](https://docs.unity.com/en-us/engine/<VERSION>/manual/unity2d/sprite/sprite-editor-window-reference/reference.md) — local `sprite/sprite-editor/sprite-editor-window-reference.html`: slice types, pivot, border, and sprite rect settings. +- [Custom Outline tab reference for the Sprite Editor window](https://docs.unity.com/en-us/engine/<VERSION>/manual/unity2d/sprite/sprite-editor-window-reference/custom-outline-editor-reference.md) — local `sprite/sprite-editor/custom-outline-editor-reference.html`: editing the outline Unity uses to build the sprite mesh. +- [Custom Physics Shape tab reference for the Sprite Editor window](https://docs.unity.com/en-us/engine/<VERSION>/manual/unity2d/sprite/sprite-editor-window-reference/custom-physics-shape-editor-reference.md) — local `sprite/sprite-editor/custom-physics-shape-editor-reference.html`: editing the physics shape used by 2D colliders. +- [9-slice a sprite](https://docs.unity.com/en-us/engine/<VERSION>/manual/unity2d/sprite/9-slice/set-sprite-9slicing.md) — local `sprite/9-slice/set-sprite-9slicing.html`: setting borders that divide a sprite into nine sections. + +### API reference + +For the provider interfaces, capabilities, and `SpriteRect` fields this skill uses, read [references/api_reference.md](references/api_reference.md). + +The API is `UnityEditor.U2D.Sprites`, part of the `com.unity.2d.sprite` package. It is versioned by package version, not Unity version (e.g. `@1.0`), so check the project's installed package version before relying on a specific class or method. + +1. Use the `unity-cli` skill to check the installed package version. +2. Fetch and cache `https://docs.unity3d.com/Packages/com.unity.2d.sprite@<VERSION>/xrefmap.yml` (replace `<VERSION>` with the installed package version, e.g. `1.0`). This file maps every public API member's fully qualified name to its docs page `href` (e.g. `href: api/UnityEditor.U2D.Sprites.ISpriteEditorDataProvider.html` => `https://docs.unity3d.com/Packages/com.unity.2d.sprite@<VERSION>/api/UnityEditor.U2D.Sprites.ISpriteEditorDataProvider.html`). +3. Grep the yml file locally for a class or method instead of refetching per lookup. Don't read the whole file. + +Always fetch the version matching the installed package rather than relying on training knowledge, since APIs are frequently marked obsolete between major versions. + +The importer APIs (`UnityEditor.AssetImporter`, `UnityEditor.TextureImporter`, `UnityEngine.SpriteAlignment`) are part of the Unity Engine. They change between Unity versions, so check the project's Unity version before relying on a specific class or method. + +1. Use the `unity-cli` skill to check the project's Unity version. +2. If the Editor install folder has a `Data/Documentation` folder (e.g. `.../Unity/Hub/Editor/6000.6.0b2/Editor/Data/Documentation`), grep the html files in the `en/ScriptReference` folder inside, and skip the remaining steps. +3. Otherwise, fetch and cache `https://docs.unity3d.com/<VERSION>/Documentation/ScriptReference/xrefmap.yml` (replace `<VERSION>` with the Unity version, e.g. `6000.3`). This file lists every public API member's fully qualified name as a `uid` (e.g. `uid: 'UnityEngine.Rigidbody.AddForce(UnityEngine.Vector3)'`). +4. Grep the yml file locally for a class or method instead of refetching per lookup. The file is large (about 6 MB), so don't read the whole file. +5. Convert the `uid` to a markdown page: remove the parameters in brackets, lowercase it, replace `.` with `/`, and add `.md`. Then fetch `https://docs.unity.com/en-us/engine/<VERSION>/script-reference/<converted uid>`. For example, `UnityEngine.Rigidbody.AddForce(UnityEngine.Vector3)` => `https://docs.unity.com/en-us/engine/<VERSION>/script-reference/unityengine/rigidbody/addforce.md`. All overloads are on the same page. + - Constructors use `ctor` (e.g. `unityengine/vector3/ctor.md`), and indexers use `item` (e.g. `unityengine/vector3/item.md`). + - For operators, fetch the class page (e.g. `unityengine/vector3.md`) and follow its link. + - Links inside the pages start with `/engine/`. Add `https://docs.unity.com/en-us` before them. + - If the page doesn't exist for that Unity version, use the `href` in the `xrefmap.yml` entry instead (e.g. `href: 'Rigidbody.AddForce.html'` => `https://docs.unity3d.com/<VERSION>/Documentation/ScriptReference/Rigidbody.AddForce.html`). + +Before Unity 6000.0 there's no `xrefmap.yml`, so skip steps 3 to 5 and fetch the class page directly, for example `https://docs.unity3d.com/<VERSION>/Documentation/ScriptReference/TextureImporter.html`. + +Always use the docs for the project's Unity version rather than relying on training knowledge, since APIs are frequently marked obsolete between versions. + +## Use the Editor + Sprite metadata (rects, borders, pivots, outlines) lives inside the importer, not in a file you can edit — reaching it means running C# through a live Editor. @@ -26,9 +104,9 @@ Run C# through the connected Editor with the `script eval` command. Discover its from `unity command --format json` rather than assuming one — the inline form is `unity command script eval --caller plugin --skill sprite-editor --code '<snippet>'`, and some Pipeline versions also register `script eval_file` for running a snippet from a file. **Check the catalog before reaching for -`script eval_file`; it is frequently absent.** `unity command` defaults to a 30 second timeout. +`script eval_file`; it is frequently absent.** `script eval`'s default timeout depends on the Pipeline version, so read it from the command's schema (`unity command --detail full --format json`) and pass `--timeout <seconds>` for a slow call. -Generates C# editor scripts to manipulate Unity sprites using ISpriteEditorDataProvider. Works with TextureImporter, PSBImporter, and custom importers. +Generate C# editor scripts that manipulate sprites through ISpriteEditorDataProvider. They work with TextureImporter, PSBImporter, and custom importers. ### Passing C# to `script eval` @@ -52,7 +130,7 @@ All generated scripts must follow the Safe Core Pattern in [references/templates **Modify Name/Rect/Border/Pivot:** Update corresponding `SpriteRect` fields (see scripts/SetPivotExample.cs for pivot examples) - Requires: `EditSpriteName`, `EditSpriteRect`, `EditBorder`, or `EditPivot` -**Add/Remove/Slice:** Create or filter `SpriteRect` array (see [references/background.md](references/background.md) for Unity 2021.2+ requirements) +**Add/Remove/Slice:** Create or filter `SpriteRect` array (see [references/background.md](references/background.md) for version-specific requirements) - Requires: `CreateAndDeleteSprite` **Set Outlines:** Get `ISpriteOutlineDataProvider` → Call `SetOutlines()` with GUID + Vector2 arrays @@ -64,3 +142,28 @@ All generated scripts must follow the Safe Core Pattern in [references/templates - **Enum assignments:** Always use enum values and cast to numeric types. Never use raw numbers. - ✅ Correct: `(int)SpriteAlignment.Center` - ❌ Wrong: `1` (magic number) + +## Final step + +Do the following checks: + +1. Check the project has zero console errors. Use `console status` for counts. +2. Stop there unless the user asked you to prove it works or you suspect a specific fault. +3. If you do enter Play mode, do it once only to chase a fault you already suspect. Read the world through `script eval` rather than adding logging. Take no screenshots as they take too much time. + +If a check fails, go back and reread the [docs pages](#full-topic-map) to find out what you missed. + +## Final report + +Give the user a concise but not dense checklist of what you did and why, including any incidental side effects (for example, settings you toggled to test something, or temporary files you created). If the user needs to follow up with more steps or decisions, list them. For example: + +``` +I made the following changes: + +[✓] Set the pivot of the `Player_Idle` sprite in `Assets/Sprites/PlayerSheet.png` to Center. + +Follow these steps to see the effect: + +1. Select `PlayerSheet.png` in the Project window. +2. Open the Sprite Editor window and select `Player_Idle` to check its pivot. +``` diff --git a/skills/using-unity/references/sprite-segment-3x3grid/SECURITY.md b/skills/using-unity/references/sprite-segment-3x3grid/SECURITY.md new file mode 100644 index 0000000..89c977e --- /dev/null +++ b/skills/using-unity/references/sprite-segment-3x3grid/SECURITY.md @@ -0,0 +1,15 @@ +# Security notes: sprite-segment-3x3grid + +This skill can have the agent run C# in the user's live Unity Editor with `unity command script eval`, to read project and Play mode state while it slices or checks sprites into a 3x3 grid. Automated skill scanners flag running code in the Editor as a powerful capability. It is intentional, and it is limited by the safeguards below. + +## Accepted risks + +| Risk | Capability | Why it is accepted | +|---|---|---| +| `SEC_POWER_CAP` | Runs C# in the user's live Editor through `unity command script eval` | It only reaches the Editor the user already has open, on their own machine, as that user, so it grants nothing they couldn't do themselves. | + +## Mitigations + +- **Only the user's own Editor.** The code runs in the Editor open on this machine. It can't reach another machine or another user's Editor. +- **Nothing left behind.** The skill tells the agent never to leave verification code in the user's scripts, and to create a restore point before changes. +- **No remote code.** Nothing downloaded from outside is executed. diff --git a/skills/using-unity/references/sprite-segment-3x3grid/sprite-segment-3x3grid.md b/skills/using-unity/references/sprite-segment-3x3grid/sprite-segment-3x3grid.md index cff84f6..1e20497 100644 --- a/skills/using-unity/references/sprite-segment-3x3grid/sprite-segment-3x3grid.md +++ b/skills/using-unity/references/sprite-segment-3x3grid/sprite-segment-3x3grid.md @@ -9,7 +9,7 @@ Segment a sprite's texture into a 3x3 grid and output a text pattern showing whi ## Important - Use the unity cli (`unity command --format json`) and the `unity-cli` and `unity-pipeline` skills for each step. -- Don't use `using` directives or unqualified types in the `snippet` for `eval`. The compiler reads using `UnityEngine` and a bare AssetDatabase, Volume, or Object causes errors (CS0246 / CS0103 / CS0104). `return` what you want to read; it arrives at `data.result.result`. +- Run C# with `unity command script eval --caller plugin --skill sprite-segment-3x3grid --code '<snippet>'`. Don't use `using` directives or unqualified types in the snippet. The compiler reads using `UnityEngine` and a bare AssetDatabase, Volume, or Object causes errors (CS0246 / CS0103 / CS0104). `return` what you want to read; it arrives at `data.result.result`. - Create a restore point you can roll back to if your changes fail. - Do only what's asked. Don't change unrelated assets or files. - Never leave verification code in the user's script. Never build logging or detection they didn't ask for. See [Final step](#final-step). @@ -191,7 +191,7 @@ Use the Sprite's `rect` property to determine the pixel region to analyze: Do the following checks: -1. Check the project has zero console errors. Use `console_status` for counts. +1. Check the project has zero console errors. Use `console status` for counts. 2. Stop there unless the user asked you to prove it works or you suspect a specific fault. If a check fails, go back and reread the [docs pages](#full-topic-map) to find out what you missed. diff --git a/skills/using-unity/references/ui-imgui/references/gui-elements.md b/skills/using-unity/references/ui-imgui/references/gui-elements.md deleted file mode 100644 index 86534fa..0000000 --- a/skills/using-unity/references/ui-imgui/references/gui-elements.md +++ /dev/null @@ -1,156 +0,0 @@ -# IMGUI Elements and Layout - -## Common GUI Elements - -| Method | Use Case | -|--------|----------| -| `GUILayout.Label()` | Text display | -| `GUILayout.Button()` | Clickable button | -| `GUILayout.TextField()` | Text input | -| `GUILayout.TextArea()` | Multi-line text input | -| `GUILayout.Toggle()` | Checkbox | -| `GUILayout.Slider()` | Value slider | -| `GUILayout.SelectionGrid()` | Button grid selection | -| `GUILayout.Toolbar()` | Toolbar buttons | - -## Editor-Specific Elements - -| Method | Use Case | -|--------|----------| -| `EditorGUILayout.PropertyField()` | Serialized property (auto) | -| `EditorGUILayout.ObjectField()` | Object reference | -| `EditorGUILayout.IntField()` | Integer input | -| `EditorGUILayout.FloatField()` | Float input | -| `EditorGUILayout.Vector3Field()` | Vector3 input | -| `EditorGUILayout.ColorField()` | Color picker | -| `EditorGUILayout.CurveField()` | Animation curve | -| `EditorGUILayout.EnumPopup()` | Enum dropdown | -| `EditorGUILayout.Popup()` | String dropdown | -| `EditorGUILayout.Foldout()` | Collapsible section | -| `EditorGUILayout.HelpBox()` | Info/warning/error box | - -## Layout Groups - -```csharp -// Horizontal -GUILayout.BeginHorizontal(); -GUILayout.Button("Left"); -GUILayout.Button("Right"); -GUILayout.EndHorizontal(); - -// Vertical -GUILayout.BeginVertical(); -GUILayout.Button("Top"); -GUILayout.Button("Bottom"); -GUILayout.EndVertical(); - -// Scroll View -scrollPos = GUILayout.BeginScrollView(scrollPos); -// ... content -GUILayout.EndScrollView(); - -// Area (absolute positioning) -GUILayout.BeginArea(new Rect(10, 10, 200, 100)); -// ... content -GUILayout.EndArea(); -``` - -## Editor Layout Groups - -```csharp -// Foldout section -showSection = EditorGUILayout.Foldout(showSection, "Section"); -if (showSection) -{ - EditorGUI.indentLevel++; - // ... content - EditorGUI.indentLevel--; -} - -// Horizontal with flex space -EditorGUILayout.BeginHorizontal(); -GUILayout.Label("Label"); -GUILayout.FlexibleSpace(); -GUILayout.Button("Action"); -EditorGUILayout.EndHorizontal(); - -// Box group -EditorGUILayout.BeginVertical("box"); -// ... content -EditorGUILayout.EndVertical(); -``` - -## Layout Options - -```csharp -// Fixed width -GUILayout.Button("Wide", GUILayout.Width(200)); - -// Fixed height -GUILayout.Button("Tall", GUILayout.Height(50)); - -// Min/Max -GUILayout.Button("Flex", GUILayout.MinWidth(100), GUILayout.MaxWidth(300)); - -// Expand -GUILayout.Button("Fill", GUILayout.ExpandWidth(true)); -``` - -## Styling - -```csharp -// Built-in styles -GUILayout.Label("Bold", EditorStyles.boldLabel); -GUILayout.Label("Large", EditorStyles.largeLabel); -GUILayout.Label("Mini", EditorStyles.miniLabel); -GUILayout.Label("Centered", EditorStyles.centeredGreyMiniLabel); - -// Custom style (cache this, don't create in OnGUI) -private GUIStyle _headerStyle; -private GUIStyle HeaderStyle => _headerStyle ??= new GUIStyle(EditorStyles.boldLabel) -{ - fontSize = 16, - alignment = TextAnchor.MiddleCenter -}; -``` - -## Spacing and Separators - -```csharp -// Fixed space -GUILayout.Space(10); - -// Flexible space (pushes elements apart) -GUILayout.FlexibleSpace(); - -// Horizontal line -EditorGUILayout.LabelField("", GUI.skin.horizontalSlider); - -// Editor separator -EditorGUILayout.Separator(); -``` - -## Disabled Groups - -```csharp -EditorGUI.BeginDisabledGroup(someCondition); -// ... disabled elements -EditorGUI.EndDisabledGroup(); - -// Or with using -using (new EditorGUI.DisabledGroupScope(someCondition)) -{ - // ... disabled elements -} -``` - -## Change Check - -```csharp -EditorGUI.BeginChangeCheck(); -value = EditorGUILayout.IntField("Value", value); -if (EditorGUI.EndChangeCheck()) -{ - // Value changed, do something -} -``` diff --git a/skills/using-unity/references/ui-imgui/references/templates.md b/skills/using-unity/references/ui-imgui/references/templates.md deleted file mode 100644 index b580bb5..0000000 --- a/skills/using-unity/references/ui-imgui/references/templates.md +++ /dev/null @@ -1,141 +0,0 @@ -# IMGUI Templates - -## EditorWindow - -```csharp -using UnityEditor; -using UnityEngine; - -public class MyToolWindow : EditorWindow -{ - [MenuItem("Tools/My Tool")] - public static void ShowWindow() - { - GetWindow<MyToolWindow>("My Tool"); - } - - private void OnGUI() - { - GUILayout.Label("My Tool", EditorStyles.boldLabel); - - // Your GUI here - } -} -``` - -## Custom Inspector - -```csharp -using UnityEditor; -using UnityEngine; - -[CustomEditor(typeof(MyComponent))] -public class MyComponentEditor : Editor -{ - public override void OnInspectorGUI() - { - DrawDefaultInspector(); - - MyComponent component = (MyComponent)target; - - if (GUILayout.Button("Do Something")) - { - component.DoSomething(); - } - } -} -``` - -## SerializedProperty Pattern (Undo Support) - -```csharp -[CustomEditor(typeof(MyComponent))] -public class MyComponentEditor : Editor -{ - private SerializedProperty myProperty; - - private void OnEnable() - { - myProperty = serializedObject.FindProperty("myField"); - } - - public override void OnInspectorGUI() - { - serializedObject.Update(); - - EditorGUILayout.PropertyField(myProperty); - - serializedObject.ApplyModifiedProperties(); - } -} -``` - -## PropertyDrawer - -```csharp -using UnityEditor; -using UnityEngine; - -[CustomPropertyDrawer(typeof(MyData))] -public class MyDataDrawer : PropertyDrawer -{ - public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) - { - EditorGUI.BeginProperty(position, label, property); - - position = EditorGUI.PrefixLabel(position, label); - - var fieldProp = property.FindPropertyRelative("field"); - EditorGUI.PropertyField(position, fieldProp, GUIContent.none); - - EditorGUI.EndProperty(); - } -} -``` - -## ScriptableWizard - -```csharp -using UnityEditor; -using UnityEngine; - -public class MyWizard : ScriptableWizard -{ - public string objectName = "New Object"; - public int count = 1; - - [MenuItem("Tools/My Wizard")] - static void CreateWizard() - { - DisplayWizard<MyWizard>("Create Objects", "Create", "Cancel"); - } - - void OnWizardCreate() - { - // Execute when "Create" clicked - } - - void OnWizardUpdate() - { - // Validate input - isValid = !string.IsNullOrEmpty(objectName) && count > 0; - } -} -``` - -## Debug Overlay (Runtime) - -```csharp -using UnityEngine; - -public class DebugOverlay : MonoBehaviour -{ - private void OnGUI() - { - GUILayout.BeginArea(new Rect(10, 10, 200, 100)); - GUILayout.Label($"FPS: {1f / Time.deltaTime:F1}"); - GUILayout.Label($"Time: {Time.time:F2}"); - GUILayout.EndArea(); - } -} -``` diff --git a/skills/using-unity/references/ui-imgui/ui-imgui.md b/skills/using-unity/references/ui-imgui/ui-imgui.md deleted file mode 100644 index f424cb2..0000000 --- a/skills/using-unity/references/ui-imgui/ui-imgui.md +++ /dev/null @@ -1,180 +0,0 @@ ---- -name: ui-imgui -description: Generates and modifies Unity IMGUI editor code such as EditorWindows, custom Inspectors, PropertyDrawers, and OnGUI scripts. Use for IMGUI or OnGUI or maintaining existing IMGUI code. ---- - -**Before proceeding:** If the user is asking about creating a **new** editor window, custom inspector, or PropertyDrawer without explicitly mentioning IMGUI/OnGUI, recommend using UI Toolkit (CreateGUI) instead, as it's the modern approach. Only proceed with IMGUI if: -- User is modifying existing IMGUI code -- User explicitly requests IMGUI/immediate mode -- The project exclusively uses IMGUI for editor tools - -When activated, read the reference files: -- [references/templates.md](references/templates.md) — EditorWindow, Inspector, PropertyDrawer templates -- [references/gui-elements.md](references/gui-elements.md) — GUI elements, layout groups, styling - -## When to Use This Skill - -**IMPORTANT:** This skill is for **legacy IMGUI code only**. Use this skill when: - -- User is maintaining/updating **existing** IMGUI editor code (files with `OnGUI()`, `OnInspectorGUI()`) -- User **explicitly requests** IMGUI/immediate mode GUI -- Project exclusively uses IMGUI for all editor tools - -**Do NOT use this skill for:** -- New editor windows (use UI Toolkit with `CreateGUI()` instead) -- New custom inspectors (use UI Toolkit instead) -- Requests that don't explicitly mention IMGUI or OnGUI - -**Legacy IMGUI is used for:** -- **Editor windows** — `EditorWindow` classes with `OnGUI()` -- **Custom inspectors** — `Editor`, `PropertyDrawer` classes with `OnInspectorGUI()` -- **Debug overlays** — `OnGUI()` in MonoBehaviour (runtime) - -IMGUI is **not** for runtime game UI — use UI Toolkit or uGUI instead. - -## Scope - -**Generate only what is requested (for legacy IMGUI code):** - -| Request | Output | Note | -|---------|--------|------| -| Editor window (IMGUI/OnGUI) | `EditorWindow` with `OnGUI()` | Only if explicitly IMGUI | -| Custom inspector (IMGUI) | `Editor` with `OnInspectorGUI()` | Only if explicitly IMGUI | -| Property drawer (IMGUI) | `PropertyDrawer` with `OnGUI()` | Only if explicitly IMGUI | -| Debug overlay | `MonoBehaviour` with `OnGUI()` | Runtime debugging | -| Update existing IMGUI script | Modify existing OnGUI code | Always appropriate | - -**Clarify if ambiguous:** -- "inspector" → Custom Editor for a specific type, or PropertyDrawer? **Also ask:** Should this use UI Toolkit (modern) or IMGUI (legacy)? -- "editor window" → **First ask:** Should this use UI Toolkit (modern/CreateGUI) or IMGUI (legacy/OnGUI)? -- "tool window" → EditorWindow with what functionality? Which UI system? - -## Conventions - -**Follow project patterns first.** Search existing editor scripts before applying defaults. - -| Type | Convention | Good | Bad | -|------|------------|------|-----| -| Script names | PascalCase | `MyToolWindow.cs` | `my-tool-window.cs` | -| EditorWindow | `[Name]Window.cs` | `LevelEditorWindow.cs` | `LevelEditor.cs` | -| Custom Editor | `[Type]Editor.cs` | `EnemyEditor.cs` | `EnemyInspector.cs` | -| PropertyDrawer | `[Type]Drawer.cs` | `RangeDrawer.cs` | `RangePropertyDrawer.cs` | -| Location | `Editor` folder | `Assets/Editor/` | `Assets/Scripts/` | - -**Editor folder is required** — Scripts using `UnityEditor` namespace must be in an `Editor` folder or they will fail to build. - -## Workflow - -1. **Analyze** — Determine script type needed (EditorWindow, Editor, PropertyDrawer, etc.) -2. **Search** — Find existing editor scripts to match patterns -3. **Follow project patterns** — Match folder structure and naming -4. **Create script** — Use appropriate base class and attributes -5. **Implement OnGUI** — Build the interface with layout groups - -## Script Structure - -### EditorWindow -``` -[MenuItem attribute] → adds to menu -ShowWindow() static method → opens window -OnGUI() → draws interface -OnEnable/OnDisable → initialization/cleanup -``` - -### Custom Editor -``` -[CustomEditor attribute] → targets component type -OnInspectorGUI() → draws inspector -OnEnable() → cache SerializedProperties -serializedObject.Update/ApplyModifiedProperties → undo support -``` - -### PropertyDrawer -``` -[CustomPropertyDrawer attribute] → targets type or attribute -OnGUI(Rect, SerializedProperty, GUIContent) → draws property -GetPropertyHeight() → custom height if needed -``` - -## Key Rules - -- **Cache GUIStyle objects** — never create new GUIStyle in OnGUI (causes memory allocation every frame) -- **Use SerializedProperty** — for proper undo/redo support in inspectors -- **Call ApplyModifiedProperties()** — after any serialized object changes -- **Use EditorGUILayout** — for editor scripts (auto-layout) -- **Use GUILayout** — for runtime OnGUI -- **Begin/End pairs** — always match BeginHorizontal with EndHorizontal, etc. -- **Editor folder required** — scripts fail to build if not in Editor folder - -## Layout Basics - -**Horizontal grouping:** -```csharp -EditorGUILayout.BeginHorizontal(); -// elements appear side by side -EditorGUILayout.EndHorizontal(); -``` - -**Vertical grouping:** -```csharp -EditorGUILayout.BeginVertical("box"); -// elements appear stacked, with box style -EditorGUILayout.EndVertical(); -``` - -**Scroll view:** -```csharp -scrollPos = EditorGUILayout.BeginScrollView(scrollPos); -// scrollable content -EditorGUILayout.EndScrollView(); -``` - -**Foldout section:** -```csharp -showSection = EditorGUILayout.Foldout(showSection, "Section Name"); -if (showSection) -{ - EditorGUI.indentLevel++; - // section content - EditorGUI.indentLevel--; -} -``` - -## Common Patterns - -**Button with action:** -```csharp -if (GUILayout.Button("Do Something")) -{ - // action here -} -``` - -**Property field with label:** -```csharp -EditorGUILayout.PropertyField(myProperty, new GUIContent("Label")); -``` - -**Object reference field:** -```csharp -myObject = (MyType)EditorGUILayout.ObjectField("Label", myObject, typeof(MyType), true); -``` - -**Disabled group:** -```csharp -EditorGUI.BeginDisabledGroup(condition); -// disabled elements -EditorGUI.EndDisabledGroup(); -``` - -## Best Practices - -- Use `SerializedObject` and `SerializedProperty` for undo support -- Cache property references in `OnEnable()` -- Use `EditorUtility.SetDirty()` only for non-serialized changes -- Use `Undo.RecordObject()` before modifying objects directly -- Use `EditorStyles` for consistent appearance -- Use `GUILayout.FlexibleSpace()` to push elements apart - -See `references/templates.md` for complete script templates. -See `references/gui-elements.md` for full element reference. diff --git a/skills/using-unity/references/ui-ugui/references/scrollview-setup.md b/skills/using-unity/references/ui-ugui/references/scrollview-setup.md deleted file mode 100644 index 91df179..0000000 --- a/skills/using-unity/references/ui-ugui/references/scrollview-setup.md +++ /dev/null @@ -1,29 +0,0 @@ -# ScrollView Setup - -ScrollRect requires a specific hierarchy to function correctly. Missing or misordered components cause jitter, duplication, or non-scrollable content. - -**Required hierarchy:** -``` -ScrollView (ScrollRect) -├── Viewport (RectTransform + Mask + Image) -│ └── Content (RectTransform + VerticalLayoutGroup + ContentSizeFitter) -│ └── [Children — static or added at runtime] -└── Scrollbar (optional) -``` - -**Setup rules:** -- **ScrollRect** component goes on the root ScrollView object -- **Viewport** must have a `Mask` component and an `Image` component (Mask requires Image) -- **Content** must have `ContentSizeFitter` with Vertical Fit set to "Preferred Size" so the scroll area grows with children -- ScrollRect references: assign Content to `Content`, Viewport to `Viewport`, and optionally assign a Scrollbar -- Content can contain static children (settings lists, about pages) or be populated dynamically at runtime - -**Dynamic population (runtime items):** -- **Clear existing children** before populating to prevent duplication on panel re-open -- Instantiate item prefabs as children of the Content object -- The ContentSizeFitter + VerticalLayoutGroup on Content will automatically size the scrollable area - -**Common failures:** -- Items duplicated on every open → Content not cleared before populating -- Content not scrollable → missing ContentSizeFitter on Content, or Viewport missing Mask -- Jitter/flickering → ContentSizeFitter conflict with parent Layout Group (see "Avoiding layout conflicts" in the main skill) diff --git a/skills/using-unity/references/ui-ugui/ui-ugui.md b/skills/using-unity/references/ui-ugui/ui-ugui.md deleted file mode 100644 index 52ebaf7..0000000 --- a/skills/using-unity/references/ui-ugui/ui-ugui.md +++ /dev/null @@ -1,276 +0,0 @@ ---- -name: ui-ugui -description: Understands, edits, and generates Unity uGUI Canvas hierarchies, RectTransforms, Layout Groups, and prefab UI. Use for requests involving Canvas, uGUI, RectTransform, or prefab UI files. ---- - -Understand existing Unity uGUI, make targeted edits, and generate new Canvas-based hierarchies. - -When working with ScrollRect/ScrollView, read the reference file: -- [references/scrollview-setup.md](references/scrollview-setup.md) — Required hierarchy, setup rules, and common failures - -## Scope - -Determine what the user is asking for: - -| Request Type | Action | -|--------------|--------| -| Question about UI | **Understand** — analyze hierarchy, explain structure | -| Change specific element | **Edit** — targeted modification only | -| Create new UI | **Generate** — create new hierarchy | -| Fix/improve existing UI | **Edit** — modify existing, don't rebuild | - -**Generate only what is requested:** - -| Request | Output | -|---------|--------| -| UI layout | Prefab or scene hierarchy only | -| "with code" / "with logic" / "functional" | Hierarchy + scripts | - -**These do NOT imply scripts:** -- "proper buttons" → well-configured Button components -- "working UI" → valid hierarchy that renders -- "menu screen" → visual layout only - -## Critical Rules - -**Namespace disambiguation:** -- Always use fully qualified type names when creating or referencing UI components -- `UnityEngine.UI.Image`, not `Image` -- `UnityEngine.UI.Button`, not `Button` -- Other namespaces in the project can cause ambiguous type errors - -**Verify before modifying:** -- Always check what exists before making changes -- Confirm parent objects exist before adding children -- Verify components are present before modifying properties -- Never assume hierarchy state — query it first - -**Incremental fixes over rebuilds:** -- When fixing issues, make targeted corrections -- Never destroy and recreate entire hierarchies to fix problems — destroyed objects cause null reference cascades -- Prefer identifying the specific broken property and fixing only that over rewriting large sections -- **When a fix fails, revert the change** before trying an alternative approach - -**One change at a time:** -- Make a single change, then verify the result -- Do not batch multiple unrelated modifications -- Be careful not to inadvertently modify or remove adjacent elements when editing a specific one -- If something fails, understand why before trying alternatives -- Avoid "shotgun debugging" with multiple simultaneous changes - -**Color and visibility:** -- **Ensure text is readable by default:** When choosing colors, ensure text contrasts with its background — but respect intentional low-contrast uses (disabled states, placeholder text, decorative elements) -- **Check visibility for new elements:** After creating UI elements, verify they have non-zero size and are within parent bounds. Elements intentionally created hidden (for later toggling, animation, etc.) are fine - -**Specification adherence:** -- **Honor user specifications exactly:** When the user provides pixel dimensions, hex colors, positions, spacing, or other exact values, apply them precisely — do not approximate or substitute -- **Minimize unrelated changes:** When editing, avoid changing properties the user didn't ask about unless a related adjustment is necessary for the fix to work - -## Conventions - -**Follow project patterns first.** Search existing files before applying defaults. - -| Type | Convention | Good | Bad | -|------|------------|------|-----| -| GameObject names | PascalCase | `SubmitButton` | `submit-button` | -| Prefab paths | Feature folders | `Assets/UI/Inventory/` | `Assets/Prefabs/UI/` | - -## Workflow - -1. **Verify state** — Check what exists in the scene/hierarchy before any action. -2. **Analyze** — Determine exactly what's needed. No extras. -3. **Search** — Find existing prefabs, canvases, assets. Don't assume paths. -4. **Follow project patterns** — Match folder structure and naming. -5. **Create or edit** — Build structure with proper anchoring, or make targeted edits. -6. **Confirm result** — Verify the change worked before moving on. - -## Canvas Setup - -Every UI needs a Canvas: - -``` -Canvas (Screen Space - Overlay or Camera) -├── CanvasScaler (Scale With Screen Size recommended) -├── GraphicRaycaster -└── [UI Content] -``` - -**CanvasScaler settings:** -- Default to UI Scale Mode "Scale With Screen Size" unless the project has a specific reason for "Constant Pixel Size" (e.g., pixel-art, fixed-resolution targets) -- Reference Resolution: Match project standards (e.g., 1920x1080) -- When creating a Canvas with Screen Space - Camera, **read the camera's reference resolution** first -- Match Width Or Height: 0.5 (balanced) -- If an existing Canvas uses "Constant Pixel Size", flag it and ask the user before changing -- Prefer anchors and Layout Groups over absolute pixel positions for layout - -## Layout Components - -**Layout Groups control child sizing:** -- When a parent has a Layout Group, it manages child RectTransforms -- Children's anchors and sizeDelta may be overridden by the parent -- Understand whether the parent or child controls size before setting values - -**Vertical/Horizontal Layout Groups:** -- Control Child Size: determines if parent sets child dimensions -- Child Force Expand: determines if children stretch to fill space -- If Control Child Size is off, children must have explicit sizes - -**Avoiding layout conflicts:** -- Do not manually set child anchors/size when parent controls them -- Do not add Layout Group to an element that should have fixed size -- Nested Layout Groups require careful configuration of each level -- When layout is wrong, check parent settings before modifying child -- ContentSizeFitter on the **same** object as a Layout Group that has Control Child Size enabled = conflict -- ContentSizeFitter on a child whose parent has Control Child Size enabled = ContentSizeFitter is overridden (wasted) -- When using ContentSizeFitter with a Layout Group parent, disable Control Child Size on the parent for the relevant axis -- Common pattern: ScrollView Content should have ContentSizeFitter + VerticalLayoutGroup where VLG controls children but ContentSizeFitter sizes the Content itself - -**Grid Layout Group:** -- For inventory grids, card layouts -- Cell Size must be set explicitly — children are sized to match -- Constraint controls row/column limits - -**Content Size Fitter:** -- Horizontal/Vertical Fit: Preferred Size -- Use on containers that should size to their content -- Requires a layout element or text component to provide preferred size - -## RectTransform Anchoring - -**Elements must have non-zero size to be visible:** -- Set explicit width/height via sizeDelta, or -- Use stretch anchors with proper offsets, or -- Let a parent Layout Group control size (with Control Child Size enabled) - -**Anchor configuration order:** -1. Set anchor preset first (corner, edge, or stretch) -2. Then set position/offset values -3. Verify the resulting size is non-zero - -**Common patterns:** -- **Stretch anchors** — for responsive elements that fill available space -- **Corner anchors** — for fixed-position, fixed-size elements -- **Edge anchors** — for elements that stretch in one direction only - -**Positioning from natural language descriptions:** -When the user describes a position (e.g., "top right", "bottom bar", "left side"): -1. Determine if it's a **corner** (fixed point), an **edge** (stretch along one axis), or **fill** (stretch both axes) -2. Set anchor min and anchor max — for corners these are the same point; for edges/fill they span a range -3. **Set pivot to match the anchor point** — pivot must align with where the element is anchored, not left at the default (0.5, 0.5). A "top right" element needs pivot at the top-right corner; a "top bar" needs pivot at the top edge center -4. Set position/offset values **after** anchors and pivot are configured - -**Visibility checklist:** -- Width and height are both greater than zero -- Element is within parent bounds -- Element is not obscured by siblings (check hierarchy order) -- Image component has a sprite or color with alpha > 0 - -## Common Components - -| Component | Use Case | -|-----------|----------| -| `Image` | Backgrounds, icons | -| `RawImage` | Render textures, videos | -| `Text (TMP)` | All text (use TextMeshPro) | -| `Button` | Clickable elements | -| `Toggle` | Checkboxes, radio buttons | -| `Slider` | Value ranges | -| `ScrollRect` | Scrollable content | -| `InputField (TMP)` | Text input | - -## Best Practices - -- Use TextMeshPro for all text (not legacy Text) -- WorldSpace UI that have text should also use Text Mesh Pro, be sure to review the project and import the TMP essentials if they are not present in the project -- If the TextMeshPro Essentials were imported be sure to close the TMP Importer Windows and the Import Unity Package Window once the assets are imported -- Organize hierarchy logically (Header, Content, Footer) -- Use Layout Groups instead of manual positioning where possible -- Set Raycast Target = false on non-interactive images -- Use sprite atlases for performance - -**Never use** `EditorApplication.ExecuteMenuItem("Window/TextMeshPro/Import TMP Essential Resources")`, unless the user asks for an interactive TMP Essentials installation. It opens a modal dialog that blocks whatever invoked it until a human dismisses it. - -**Do not use** `AssetDatabase.ImportPackage()` for TMP resources, instead `TMP_PackageResourceImporter.ImportResources()` is the canonical non-interactive API. - -## Interaction Readiness - -Before completing any UI that contains interactive elements, verify: - -1. **EventSystem** must exist in the scene (exactly one) -2. **GraphicRaycaster** must be on the Canvas -3. **Raycast Target = true** on interactive elements (and false on non-interactive ones to avoid blocking) -4. **Button.onClick should be wired** (via inspector or script) — only when scripts or logic were requested - -If the first three are missing, interactive elements will exist visually but fail silently. - -## Understanding - -When the user asks questions about existing UI: - -**Read the hierarchy first.** Don't assume — always inspect the scene or prefab before answering. - -**Analyze structure:** -- Identify the Canvas and its render mode -- Map the parent-child relationships -- Identify which Layout Groups control which children -- Check RectTransform anchor configurations - -**Answer questions about:** -- "What does this button do?" → Explain component, hierarchy position, event wiring -- "How is this laid out?" → Describe Layout Groups, anchoring, hierarchy -- "Why is this invisible?" → Check size, anchors, parent bounds, component state -- "What controls this element's size?" → Trace Layout Group settings or anchors - -## Editing - -For targeted changes to existing UI: - -**Read before editing.** Always inspect the current state first. - -**Edit workflow:** -1. Verify the target object exists -2. Identify the specific property or component to change -3. Make the minimal change required -4. Verify the result before proceeding - -**Never destroy to fix:** -- Destroying objects cascades to null references elsewhere -- Fix properties in place rather than recreating -- If an element must be removed, update all references first - -## C# (Only When Requested) - -- Use fully qualified UI types to avoid namespace conflicts -- Use `[SerializeField]` for inspector references -- Cache component references in Awake() -- Use events/delegates for button callbacks -- Place scripts in same folder as prefabs (follow project patterns) - -**Component references:** -- Verify referenced objects exist before accessing them -- Handle cases where serialized references may be null -- When wiring up references, confirm the target component is present - -## Error Recovery - -When something goes wrong: - -**Stop and diagnose:** -- Identify the exact error or symptom -- Determine the root cause before attempting fixes -- Do not make speculative changes - -**Fix incrementally:** -- Address one issue at a time -- Verify each fix before moving to the next -- Keep track of what was changed - -**Avoid destructive patterns:** -- "Start fresh" strategies destroy working elements along with broken ones -- Rebuilding entire hierarchies creates more problems than it solves -- Prefer surgical fixes to wholesale replacements - -**When stuck:** -- Re-verify the current state of the hierarchy -- Check if previous changes were actually applied -- Consider if the approach itself is wrong rather than the implementation diff --git a/skills/using-unity/references/ui-uitk/references/common-issues.md b/skills/using-unity/references/ui-uitk/references/common-issues.md deleted file mode 100644 index b0d8140..0000000 --- a/skills/using-unity/references/ui-uitk/references/common-issues.md +++ /dev/null @@ -1,74 +0,0 @@ -# Common USS/UXML Issues - -## Transitions on :hover - -Transitions must be defined on the base class, not the hover state: - -```uss -/* WRONG - won't animate on hover-out */ -.button:hover { - background-color: blue; - transition-duration: 0.2s; -} - -/* CORRECT */ -.button { - background-color: white; - transition-duration: 0.2s; -} -.button:hover { - background-color: blue; -} -``` - -## Hardcoded Percentage Widths - -Avoid hardcoded percentages for flexible layouts: - -```uss -/* AVOID */ -.column { - width: 33%; -} - -/* PREFER */ -.column { - flex-grow: 1; -} -``` - -## Unclosed Brackets - -Always ensure brackets are properly closed: - -```uss -/* WRONG - missing closing bracket */ -.panel { - padding: 16px; - -.button { - color: white; -} - -/* CORRECT */ -.panel { - padding: 16px; -} - -.button { - color: white; -} -``` - -## Referencing Unity Theme - -**Do NOT reference `UnityDefaultRuntimeTheme.tss`** or built-in theme icons. - -Create custom styles or reuse project assets instead. - -## Performance Issues - -- **Inline styles** cause per-element memory overhead -- **`:hover` on parents** with many children invalidates entire hierarchies -- **Many classes per element** decreases selector performance linearly -- **Large hierarchies** are the main performance factor diff --git a/skills/using-unity/references/ui-uitk/references/custom-elements.md b/skills/using-unity/references/ui-uitk/references/custom-elements.md deleted file mode 100644 index b79651c..0000000 --- a/skills/using-unity/references/ui-uitk/references/custom-elements.md +++ /dev/null @@ -1,241 +0,0 @@ -# Custom VisualElements in UI Toolkit - -Guide for creating custom VisualElements using Unity 6+ `[UxmlElement]` and `[UxmlAttribute]` attributes. - -## Table of Contents - -- [Overview](#overview) -- [Requirements](#requirements) -- [Supported Property Types](#supported-property-types) -- [Advanced Patterns](#advanced-patterns) -- [Best Practices](#best-practices) -- [UXML Namespace Declaration](#uxml-namespace-declaration) -- [UI Builder Integration](#ui-builder-integration) -- [Summary](#summary) - -## Overview - -Unity 6+ uses attribute-based custom elements. The old factory pattern (`IUxmlFactory`, `UxmlTraits`) is **deprecated**. - -### ⚠ CRITICAL: Namespace Declaration - -**Never include assembly names in UXML namespace declarations:** - -```xml -❌ WRONG: xmlns:custom="Game.UI.Custom, Assembly-CSharp" -✅ CORRECT: xmlns:custom="Game.UI.Custom" -``` - -**Format**: `xmlns:prefix="Namespace.Path"` (namespace only, no assembly) - -### Basic Pattern - -```csharp -[UxmlElement] -public partial class MyElement : VisualElement -{ - [UxmlAttribute] - public string myValue { get; set; } -} -``` - -```xml -<ui:UXML xmlns:ui="UnityEngine.UIElements" - xmlns:custom="Game.UI.Custom"> - <custom:MyElement my-value="Hello" /> -</ui:UXML> -``` - -## Requirements - -1. **[UxmlElement]** attribute on the class -2. **partial** keyword required -3. Inherit from **VisualElement** or subclass -4. **[UxmlAttribute]** on exposed properties - -### Property Naming - -C# camelCase → UXML kebab-case: -- `myStringValue` → `my-string-value` -- `maxHealth` → `max-health` - -### Example - -```csharp -[UxmlElement] -public partial class CustomLabel : Label -{ - [UxmlAttribute] - public Color textColor { get; set; } = Color.white; - - [UxmlAttribute] - public int fontSize { get; set; } = 14; - - public CustomLabel() - { - RegisterCallback<GeometryChangedEvent>(evt => { - style.color = textColor; - style.fontSize = fontSize; - }); - } -} -``` - -```xml -<custom:CustomLabel text="Hello" text-color="rgb(255,215,0)" font-size="24" /> -``` - -## Supported Property Types - -**Basic**: `string`, `int`, `float`, `bool`, `Color` -**Unity**: `Texture2D`, `Sprite`, `Font` -**Enums**: Any enum type -**Collections**: `List<T>`, `T[]` - -### Image Handling - -**Static images** (don't change) → Use USS: -```css -.icon { background-image: url('project://Assets/UI/Icons/fireball.png'); } -``` - -**Dynamic images** (change per instance) → Use `[UxmlAttribute]`: -```csharp -[UxmlAttribute] -public Sprite portrait { get; set; } // Different per character -``` - -## Advanced Patterns - -### Validation Attributes - -```csharp -[UxmlAttribute] -[Range(0, 100)] -[Tooltip("Current health value")] -public float health { get; set; } = 100f; -``` - -Improves UI Builder inspector experience. - -### Custom Attribute Names - -```csharp -[UxmlAttribute("hp")] -public float health { get; set; } // Use "hp" in UXML -``` - -### Custom Type Converters - -Use `UxmlAttributeConverter<T>` when a property's type is not natively supported by UXML (e.g. structs, complex data objects). An example below implements `FromString` to parse the UXML attribute string into the specified type, then register it with `[UxmlAttributeConverter]` on the property. - -```csharp -public class HealthDataConverter : UxmlAttributeConverter<HealthData> -{ - public override HealthData FromString(string value) - { - var parts = value.Split(','); - return new HealthData { current = float.Parse(parts[0]), max = float.Parse(parts[1]) }; - } -} - -[UxmlAttribute] -[UxmlAttributeConverter(typeof(HealthDataConverter))] -public HealthData healthData { get; set; } -``` - -### Custom Property Drawers - -Create custom UI Builder inspector controls for your attributes: - -```csharp -// 1. Custom attribute -public class SliderDrawerAttribute : PropertyAttribute { } - -// 2. Property drawer -[CustomPropertyDrawer(typeof(SliderDrawerAttribute))] -public class SliderDrawerPropertyDrawer : PropertyDrawer -{ - public override VisualElement CreatePropertyGUI(SerializedProperty property) - { - var field = new SliderInt(0, 100) { label = property.displayName }; - field.BindProperty(property); - return field; - } -} - -// 3. Usage -[UxmlElement] -public partial class StyledButton : Button -{ - [UxmlAttribute] - [SliderDrawer] - public int intensity { get; set; } = 50; -} -``` - -**Override existing properties** with custom drawers: - -```csharp -[UxmlElement] -public partial class CustomIntField : IntegerField -{ - // Override base 'value' property to use slider drawer in UI Builder - [UxmlAttribute("value"), SliderDrawer] - internal int myValue - { - get => this.value; - set => this.value = value; - } -} -``` - -This customizes how properties appear in the UI Builder inspector. - - -## Best Practices - -1. **Always use `partial`** - Required for [UxmlElement] -2. **Provide defaults** - `public float radius { get; set; } = 30f;` -3. **Update on changes** - Use property setters to call `UpdateVisuals()` or `MarkDirtyRepaint()` -4. **Use backing fields** - When validation or change detection needed -5. **USS for styling** - Add class names and style via USS, not inline styles -6. **Static images → USS, Dynamic → C#** - Use USS `background-image` for fixed images -7. **Document elements** - Add XML comments for better developer experience - -## UXML Namespace Declaration - -### Rules - -1. **Namespace only** - No assembly name, no commas -2. **Exact match** - Must match C# namespace exactly (case-sensitive) -3. **Format**: `xmlns:prefix="Namespace.Path"` - -### Examples - -```xml -<!-- ✅ Single namespace --> -<ui:UXML xmlns:ui="UnityEngine.UIElements" - xmlns:custom="Game.UI.Custom"> - <custom:RadialProgress /> -</ui:UXML> - -<!-- ✅ Multiple namespaces --> -<ui:UXML xmlns:ui="UnityEngine.UIElements" - xmlns:hud="Game.UI.HUD" - xmlns:menu="Game.UI.Menu"> - <hud:HealthBar /> - <menu:SettingsPanel /> -</ui:UXML> -``` - -### Common Mistakes - -```xml -❌ xmlns:custom="Game.UI.Custom, Assembly-CSharp" (assembly name) -❌ xmlns:custom="game.ui.custom" (wrong case) -❌ xmlns:custom="Custom" (incomplete) -❌ xmlns:custom="Game.UI.Custom.RadialProgress" (class name) - -✅ xmlns:custom="Game.UI.Custom" (correct) -``` diff --git a/skills/using-unity/references/ui-uitk/references/painter2d.md b/skills/using-unity/references/ui-uitk/references/painter2d.md deleted file mode 100644 index 690ff0b..0000000 --- a/skills/using-unity/references/ui-uitk/references/painter2d.md +++ /dev/null @@ -1,282 +0,0 @@ -# Custom Visuals with Painter2D - -## Table of Contents - -- [The Pattern](#the-pattern) -- [Canvas-to-Painter2D Mapping](#canvas-to-painter2d-mapping) -- [Gradient Fills](#gradient-fills) -- [GradientElement — Full Example](#gradientelement--full-example) -- [Other Use Cases](#other-use-cases) -- [Rules](#rules) - -USS cannot draw gradients, arbitrary shapes, arcs, or procedural patterns. For these, use the **Painter2D** API via the `generateVisualContent` callback. - -Painter2D is modeled on the **HTML Canvas 2D** context — `BeginPath`, `MoveTo`, `LineTo`, `Arc`, `BezierCurveTo`, `Fill`, `Stroke` all map directly. Key differences from Canvas: text is drawn via `ctx.DrawText()` on the `MeshGenerationContext` (not on Painter2D itself), no `drawImage()` (use `fillTexture` or child elements with USS `background-image`), angles use `Angle.Degrees()` / `Angle.Turns()` structs, arc direction is an enum (`ArcDirection.Clockwise` / `.CounterClockwise`), and coordinates are local to the element's content rect. - -**Drawing text:** Use `ctx.DrawText(string text, Vector2 pos, float fontSize, Color color, FontAsset font)` on the `MeshGenerationContext` directly. Pass `null` for `font` to use the element's USS font. This is useful when text must be positioned precisely within custom-drawn visuals — for simpler cases, child `Label` elements are easier. - -## The Pattern - -Every custom-drawn element: extend `VisualElement` directly (never `Label`, `Button`, etc. — Painter2D won't render correctly on those), subscribe to `generateVisualContent`, draw with `ctx.painter2D`, call `MarkDirtyRepaint()` when properties change. For animations, call `MarkDirtyRepaint()` every frame from an update loop. - -```csharp -[UxmlElement] -public partial class MyCustomVisual : VisualElement -{ - float m_Value = 0.5f; - - [UxmlAttribute] - public float Value - { - get => m_Value; - set { m_Value = value; MarkDirtyRepaint(); } - } - - public MyCustomVisual() - { - generateVisualContent += OnGenerateVisualContent; - } - - void OnGenerateVisualContent(MeshGenerationContext ctx) - { - float w = contentRect.width; - float h = contentRect.height; - if (w < 1f || h < 1f) return; - - var painter = ctx.painter2D; - // ... drawing commands - } -} -``` - -Name classes to match their purpose — `GradientCard`, `RadialProgress`, `WaveformDisplay`, etc. - -## Canvas-to-Painter2D Mapping - -| HTML Canvas 2D | Unity Painter2D | -|----------------|-----------------| -| `beginPath()` | `BeginPath()` | -| `moveTo(x, y)` | `MoveTo(new Vector2(x, y))` | -| `lineTo(x, y)` | `LineTo(new Vector2(x, y))` | -| `arc(cx, cy, r, start, end)` | `Arc(Vector2 center, float radius, Angle start, Angle end, ArcDirection dir)` | -| `arcTo(x1, y1, x2, y2, r)` | `ArcTo(Vector2 p1, Vector2 p2, float radius)` | -| `bezierCurveTo(...)` | `BezierCurveTo(Vector2 ctrl1, Vector2 ctrl2, Vector2 end)` | -| `quadraticCurveTo(...)` | `QuadraticCurveTo(Vector2 ctrl, Vector2 end)` | -| `closePath()` | `ClosePath()` | -| `rect(x, y, w, h)` | **No equivalent** — trace manually with `MoveTo`/`LineTo`/`ClosePath` | -| `fill()` | `Fill(FillRule rule = NonZero)` — use `OddEven` for holes/cutouts | -| `stroke()` | `Stroke()` | -| `lineWidth` | `lineWidth` | -| `strokeStyle` | `strokeColor` / `strokeGradient` / `strokeFillGradient` | -| `fillStyle` | `fillColor` / `fillGradient` / `fillTexture` | -| `lineCap` | `lineCap` — `LineCap.Butt` (default), `.Round`, `.Square` | -| `lineJoin` | `lineJoin` — `LineJoin.Miter` (default), `.Bevel`, `.Round` | -| `setLineDash([...])` | `SetDashPattern(float[])` | -| `lineDashOffset` | `dashOffset` | - -Both `Fill()` and `Stroke()` can be called on the same path. - -Angle helpers: `Angle.Degrees(float)`, `Angle.Radians(float)`, `Angle.Turns(float)`. - -## Gradient Fills - -USS has no `linear-gradient()` or `radial-gradient()`. Use `FillGradient`: - -```csharp -// Linear — two-color shorthand -FillGradient.MakeLinearGradient(Color startColor, Color endColor, Vector2 start, Vector2 end, AddressMode mode) -// Linear — multi-stop via Gradient object -FillGradient.MakeLinearGradient(Gradient gradient, Vector2 start, Vector2 end, AddressMode mode) - -// Radial — two-color shorthand -FillGradient.MakeRadialGradient(Color startColor, Color endColor, Vector2 center, float radius, Vector2 focus, AddressMode mode) -// Radial — multi-stop via Gradient object -FillGradient.MakeRadialGradient(Gradient gradient, Vector2 center, float radius, Vector2 focus, AddressMode mode) -``` - -`AddressMode`: `Clamp` (extend edge color), `Repeat` (tile), `Mirror` (reflect). - -**Linear gradient direction** — controlled by start/end points: - -| Direction | Start | End | -|-----------|-------|-----| -| Top → Bottom | `(0, 0)` | `(0, height)` | -| Left → Right | `(0, 0)` | `(width, 0)` | -| Diagonal | `(0, 0)` | `(width, height)` | - -**Radial gradient** — set `focus` off-center to shift the bright spot. - -## GradientElement — Full Example - -A custom element rendering a linear gradient with rounded corners and optional border stroke. All properties exposed as UXML attributes. - -```csharp -using UnityEngine; -using UnityEngine.UIElements; - -[UxmlElement] -public partial class GradientElement : VisualElement -{ - Color m_StartColor = new Color(0.13f, 0.59f, 0.95f); - Color m_EndColor = new Color(0.61f, 0.15f, 0.69f); - Color m_BorderColor = Color.white; - float m_BorderWidth = 2f; - float m_CornerRadius = 8f; - float m_GradientAlpha = 1f; - - [UxmlAttribute] - public Color StartColor - { - get => m_StartColor; - set { m_StartColor = value; MarkDirtyRepaint(); } - } - - [UxmlAttribute] - public Color EndColor - { - get => m_EndColor; - set { m_EndColor = value; MarkDirtyRepaint(); } - } - - [UxmlAttribute] - public Color BorderColor - { - get => m_BorderColor; - set { m_BorderColor = value; MarkDirtyRepaint(); } - } - - [UxmlAttribute] - public float BorderWidth - { - get => m_BorderWidth; - set { m_BorderWidth = value; MarkDirtyRepaint(); } - } - - [UxmlAttribute] - public float CornerRadius - { - get => m_CornerRadius; - set { m_CornerRadius = value; MarkDirtyRepaint(); } - } - - [UxmlAttribute] - public float GradientAlpha - { - get => m_GradientAlpha; - set { m_GradientAlpha = Mathf.Clamp01(value); MarkDirtyRepaint(); } - } - - public GradientElement() - { - generateVisualContent += OnGenerateVisualContent; - } - - void OnGenerateVisualContent(MeshGenerationContext ctx) - { - float w = contentRect.width; - float h = contentRect.height; - if (w < 1f || h < 1f) - return; - - DrawGradientBackground( - ctx.painter2D, w, h, - m_StartColor, m_EndColor, m_GradientAlpha, - m_CornerRadius, - m_BorderColor, m_BorderWidth); - } - - static void DrawGradientBackground( - Painter2D painter, - float width, float height, - Color startColor, Color endColor, float alpha, - float cornerRadius, - Color borderColor, float borderWidth) - { - float r = Mathf.Min(cornerRadius, Mathf.Min(width, height) * 0.5f); - - var start = startColor; - var end = endColor; - start.a *= alpha; - end.a *= alpha; - - painter.fillGradient = FillGradient.MakeLinearGradient( - BuildGradient(start, end), - new Vector2(0f, 0f), - new Vector2(0f, height), - AddressMode.Clamp); - - painter.BeginPath(); - TraceRoundedRect(painter, 0f, 0f, width, height, r); - painter.Fill(); - - if (borderWidth <= 0f) - return; - - float half = borderWidth * 0.5f; - painter.strokeColor = borderColor; - painter.lineWidth = borderWidth; - painter.lineJoin = LineJoin.Round; - - painter.BeginPath(); - TraceRoundedRect( - painter, half, half, - width - borderWidth, height - borderWidth, - Mathf.Max(0f, r - half)); - painter.Stroke(); - } - - static Gradient BuildGradient(Color start, Color end) - { - var gradient = new Gradient(); - gradient.SetKeys( - new[] { new GradientColorKey(start, 0f), new GradientColorKey(end, 1f) }, - new[] { new GradientAlphaKey(start.a, 0f), new GradientAlphaKey(end.a, 1f) }); - return gradient; - } - - static void TraceRoundedRect(Painter2D p, float x, float y, float w, float h, float r) - { - p.MoveTo(new Vector2(x + r, y)); - p.LineTo(new Vector2(x + w - r, y)); - p.ArcTo(new Vector2(x + w, y), new Vector2(x + w, y + r), r); - p.LineTo(new Vector2(x + w, y + h - r)); - p.ArcTo(new Vector2(x + w, y + h), new Vector2(x + w - r, y + h), r); - p.LineTo(new Vector2(x + r, y + h)); - p.ArcTo(new Vector2(x, y + h), new Vector2(x, y + h - r), r); - p.LineTo(new Vector2(x, y + r)); - p.ArcTo(new Vector2(x, y), new Vector2(x + r, y), r); - p.ClosePath(); - } -} -``` - -### Usage in UXML - -```uxml -<ui:UXML xmlns:ui="UnityEngine.UIElements"> - <ui:Style src="Screen.uss" /> - <GradientElement class="gradient-card" - start-color="#2196F3" end-color="#9C27B0" - gradient-alpha="0.9" corner-radius="12" - border-color="#FFFFFF" border-width="1"> - <ui:Label text="Card Title" class="card-title" /> - <ui:Label text="Description text goes here" class="card-desc" /> - </GradientElement> -</ui:UXML> -``` - -The element participates in flexbox, accepts children, and can be styled with USS for sizing, padding, and margin. The gradient draws behind child content. - -## Other Use Cases - -Painter2D handles any visual USS cannot express — progress rings (`Arc()` with dynamic `endAngle`), custom shapes (polygons, stars, badges), charts (bar fills, pie segments, sparklines), decorative elements (wave patterns, bezier flourishes), and animated visuals (drive properties from C#, call `MarkDirtyRepaint()` each frame). - -## Rules - -- **Extend `VisualElement` directly** — never `Label`, `Button`, etc. -- **Guard zero dimensions** — `if (contentRect.width < 1f || contentRect.height < 1f) return;` -- **`BeginPath()` before every path** — omitting it causes silent failures -- **No `Rect()` method** — Painter2D has no rectangle convenience method. Trace rectangles manually with `MoveTo`/`LineTo`/`ClosePath` (see `TraceRoundedRect` in the gradient example) -- **Set style properties before `BeginPath()`** — `lineWidth`, `strokeColor`, `fillColor`, etc. -- **Never mutate the element inside `generateVisualContent`** — no style changes, no adding children, no `MarkDirtyRepaint()` from within the callback -- **`LineCap.Butt` for precise arc endpoints** — `Round` extends past the endpoint by half the line width diff --git a/skills/using-unity/references/ui-uitk/references/pointermanipulator-guide.md b/skills/using-unity/references/ui-uitk/references/pointermanipulator-guide.md deleted file mode 100644 index 2afa01c..0000000 --- a/skills/using-unity/references/ui-uitk/references/pointermanipulator-guide.md +++ /dev/null @@ -1,94 +0,0 @@ -# UI Toolkit Manipulator Reference - -Pointer Manipulators handle pointer interactions like drag and drop, click, hover, and gestures in Unity UI Toolkit. - -## What is a Manipulator? - -A `Manipulator` is an event handler class attached to `VisualElement`s to add interactive behavior. They encapsulate interaction logic and can be reused across multiple elements. - -## Base Pattern - -Pointer Manipulators inherit from `PointerManipulator` and override: -- `RegisterCallbacksOnTarget()` — Subscribe to events when attached -- `UnregisterCallbacksFromTarget()` — Unsubscribe when detached - -Attach with: `element.AddManipulator(new YourManipulator())` - -## Drag and Drop Approach - -### Drag and Drop Code Design -1. **PointerDown** — Capture pointer, store pointer start position, store dragged element reference, mark as dragging, set to Aboslute positioning, and BringToFront - -```csharp -_isDragging = true; -target.style.position = Position.Absolute; -target.BringToFront(); -target.usageHints = UsageHints.DynamicTransform; -``` - -2. **PointerMove** — Update dragged element position relative to the pointer, check if pointer is over valid drop target. ALWAYS use the StyleTranslate API for drag and drop and updating element position unless otherwise specified. - -Example of using StyleTranslate API: -```csharp -target.style.translate = new StyleTranslate(newWorldPosition); -``` - -3. **PointerUp** — If over drop target or find nearest overlapping target, execute drop logic (move element, trigger callback), release pointer -4. **PointerCaptureOut** — Finalize drop and raise event - -### Drop Target Detection -Use `VisualElement.panel.Pick(position)` or check bounds with `worldBound.Contains(position)` to find elements under the pointer. - -### Visual Feedback -Add/remove USS classes on drag start/end for hover states, drag shadows, or drop zone highlights: -```csharp -target.AddToClassList("dragging"); -dropZone.AddToClassList("drop-zone-active"); -``` - -## Best Practices -- Use USS classes for visual states instead of inline `element.style.*` properties -- Validate drop targets before executing drop logic -- Use `evt.StopPropagation();` to prevent dragged items from behaving like buttons or interacting unexpectedly -- To ensure dragged item is always on top use `BringToFront()` -- Decide the `pickingMode` for the dragged item to ensure the slot underneath is detected and revert to proper state after dropping - -## Common Enhancements - -- **Constrain to bounds** — Clamp position to parent or screen bounds -- **StyleTranslation API** - Use `target.style.translate = new StyleTranslate(newWorldPosition)` to avoid style pass updates -- **Performance** - Use Usage Hints and `UsageHints.DynamicTransform;` for better performance -- **Drop validation** — Check if drop target accepts this element type -- **Revert on invalid drop** — Animate back to start position if dropped outside valid zone - -## Inventory and Crafting Systems - -When users request inventory or crafting systems, first determine requirements: - -### Ask Users First -- "Should players be able to drag and drop items between slots?" -- "Should items snap to grid positions or specific equipment slots?" -- "Do items stack? Do they have quantities?" - -If drag-and-drop is NOT needed, create static visual layout only (UXML/USS). - -### When to Use Drag-Drop - -**Inventory systems need drag-drop when:** -- Players move items between slots (inventory, equipment, hotbar) -- Items can be equipped to specific slots (head, chest, weapon) -- Players organize or sort their inventory - -**Crafting systems need drag-drop when:** -- Players place ingredients into crafting slots -- Players combine items by dragging them together -- Recipe slots require specific item types - -**Implementation Checklist** -When implementing drag-drop for inventory/crafting: -- Created manipulator and callback methods for draggable UI element -- Created UI element or slots as a drop zone -- Added USS classes for dragging and drop states -- Stored item data separately from visual elements (use data binding or C# dictionaries) -- Validated drop targets before executing drop -- Added visual feedback: drag shadows, slot highlighting, hover states diff --git a/skills/using-unity/references/ui-uitk/references/svg-icons.md b/skills/using-unity/references/ui-uitk/references/svg-icons.md deleted file mode 100644 index c498247..0000000 --- a/skills/using-unity/references/ui-uitk/references/svg-icons.md +++ /dev/null @@ -1,136 +0,0 @@ -# SVG Icon Generation (Unity 6.3+) - -## Table of Contents - -- [When to Use SVG](#when-to-use-svg) -- [Priority Order](#priority-order) -- [SVG Format](#svg-format) -- [Common Icon Examples](#common-icon-examples) -- [Usage in Unity](#usage-in-unity) -- [Tips](#tips) - -## When to Use SVG - -**Prefer SVG for:** -- Simple icons (arrows, chevrons, checkmarks) -- Geometric shapes -- UI symbols (close, menu, settings) -- Any icon that can be drawn with paths - -**Use image generators for:** -- Complex illustrations -- Photorealistic content -- Detailed artwork -- Gradients with many stops - -## Priority Order - -1. **Reuse existing project icons** — always search first -2. **Generate SVG** — fast, resolution-independent, low cost -3. **Image generators** — last resort, slower and higher cost - -## SVG Format - -Unity imports SVG as VectorImage assets. Use standard SVG markup: - -```svg -<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> - <path d="..." stroke="currentColor" stroke-width="2" fill="none"/> -</svg> -``` - -## Common Icon Examples - -### Arrow Right -```svg -<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> - <path d="M8 4l8 8-8 8" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"/> -</svg> -``` - -### Arrow Left -```svg -<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> - <path d="M16 4l-8 8 8 8" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"/> -</svg> -``` - -### Chevron Down -```svg -<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> - <path d="M4 8l8 8 8-8" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"/> -</svg> -``` - -### Checkmark -```svg -<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> - <path d="M4 12l6 6L20 6" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"/> -</svg> -``` - -### Close (X) -```svg -<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> - <path d="M6 6l12 12M18 6L6 18" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round"/> -</svg> -``` - -### Plus -```svg -<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> - <path d="M12 4v16M4 12h16" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round"/> -</svg> -``` - -### Minus -```svg -<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> - <path d="M4 12h16" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round"/> -</svg> -``` - -### Menu (Hamburger) -```svg -<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> - <path d="M4 6h16M4 12h16M4 18h16" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round"/> -</svg> -``` - -### Settings (Gear) -```svg -<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> - <circle cx="12" cy="12" r="3" stroke="currentColor" stroke-width="2" fill="none"/> - <path d="M12 1v4M12 19v4M4.22 4.22l2.83 2.83M16.95 16.95l2.83 2.83M1 12h4M19 12h4M4.22 19.78l2.83-2.83M16.95 7.05l2.83-2.83" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round"/> -</svg> -``` - -### Search (Magnifying Glass) -```svg -<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> - <circle cx="10" cy="10" r="6" stroke="currentColor" stroke-width="2" fill="none"/> - <path d="M14.5 14.5L20 20" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round"/> -</svg> -``` - -## Usage in Unity - -1. Save SVG file to project (e.g., `Assets/UI/Icons/arrow-right.svg`) -2. Unity auto-imports as VectorImage -3. Set "Generated Asset Type" to "UI Toolkit Vector Image" in Inspector -4. Reference in USS: - -```uss -.icon-arrow { - background-image: url("project://database/Assets/UI/Icons/arrow-right.svg"); - width: 24px; - height: 24px; -} -``` - -## Tips - -- Use `viewBox="0 0 24 24"` for consistent sizing -- Use `stroke="currentColor"` for tintable icons -- Use `fill="none"` for outline-style icons -- Keep paths simple — complex SVGs may not render correctly diff --git a/skills/using-unity/references/ui-uitk/references/ui-runtime-binding.md b/skills/using-unity/references/ui-uitk/references/ui-runtime-binding.md deleted file mode 100644 index b2e2a68..0000000 --- a/skills/using-unity/references/ui-uitk/references/ui-runtime-binding.md +++ /dev/null @@ -1,234 +0,0 @@ -# Runtime Data Binding Reference - -## Table of Contents - -- [Core Concepts](#core-concepts) -- [Data Source Setup](#data-source-setup) -- [CRITICAL: Always Use nameof()](#critical-always-use-nameof) -- [Explicit Binding Element](#explicit-binding-element) -- [C# SetBinding (Programmatic)](#c-setbinding-programmatic) -- [PanelRenderer with Bindings](#panelrenderer-with-bindings) - -Unity UI Toolkit runtime data binding for efficient UI updates. - -## Core Concepts - -**Use binding when:** -- Connecting game state to UI (health, score, ammo) -- Multiple UI elements display the same data -- Data changes frequently but predictably - -**Avoid binding when:** -- One-time UI updates -- Per-frame updates (use direct property sets) -- Simple direct property assignment is clearer - -## Data Source Setup - -### Required: [CreateProperty] Attribute - -```csharp -using Unity.Properties; -using UnityEngine; - -public class PlayerData -{ - [CreateProperty] - public int Health { get; set; } - - // the private serialized field here helps the user see the property in the editor but do not create the property on the private member unless requested - [SerializeField, DontCreateProperty] - private float m_Speed; - - // the public member gets a property created out of it so we bind to this property - [CreateProperty] - public float Speed - { - get => m_Speed; - set => m_Speed = value; - } -} -``` - - -## CRITICAL: Always Use nameof() -```csharp -element.SetBinding("value", new DataBinding -{ - dataSourcePath = new PropertyPath(nameof(HealthData.HealthPercentage)) -}); -``` - -**Why nameof():** -- Compile-time safety (no typos) -- Refactoring support -- IntelliSense/autocomplete -- No capitalization errors - -**Nested properties:** -```csharp -dataSourcePath = new PropertyPath($"{nameof(PlayerData)}.{nameof(PlayerData.Health)}.{nameof(HealthData.Current)}") -``` - -### Explicit Binding Element - -```xml -<UXML xmlns:ui="UnityEngine.UIElements" xmlns:engine="UnityEngine.UIElements"> - <Slider name="volume-slider"> - <Bindings> - <engine:DataBinding - property="value" - data-source-path="MasterVolume" - binding-mode="TwoWay"/> - </Bindings> - </Slider> -</UXML> -``` - -The datasource can be set in the root VisualElement like: -```xml - <ui:VisualElement name="root" data-source="project://database/Assets/Scripts/PlayerData.asset?fileID=11400000&guid=976f7b99fc1424923aee5b5657723366&type=2#PlayerData" class="root"> -``` -This is so that UIBuilder can also read the datasource and preview the binding and control. - -```csharp -private void OnEnable() -{ - var root = GetComponent<UIDocument>().rootVisualElement; - root.dataSource = m_Settings; -} -``` - -## C# SetBinding (Programmatic) - -### Basic Pattern - -```csharp -using UnityEngine; -using UnityEngine.UIElements; - -[RequireComponent(typeof(UIDocument))] -public class HealthBarController : MonoBehaviour -{ - [SerializeField] private HealthData m_HealthData; - private Label m_HealthLabel; - private ProgressBar m_HealthBar; - - private void OnEnable() - { - var root = GetComponent<UIDocument>().rootVisualElement; - m_HealthLabel = root.Q<Label>("health-label"); - m_HealthBar = root.Q<ProgressBar>("health-bar"); - - m_HealthLabel.SetBinding("text", new DataBinding - { - dataSourcePath = new PropertyPath(nameof(HealthData.HealthText)) - }); - - m_HealthBar.SetBinding("value", new DataBinding - { - dataSourcePath = new PropertyPath(nameof(HealthData.HealthPercentage)) - }); - - m_HealthLabel.dataSource = m_HealthData; - m_HealthBar.dataSource = m_HealthData; - } - - private void OnDisable() - { - if (m_HealthLabel?.HasBinding("text") == true) - m_HealthLabel.ClearBinding("text"); - if (m_HealthBar?.HasBinding("value") == true) - m_HealthBar.ClearBinding("value"); - } -} -``` - -### Binding Modes - -```csharp -element.SetBinding("text", new DataBinding -{ - dataSourcePath = new PropertyPath(nameof(Data.Score)), - bindingMode = BindingMode.ToTarget -}); - -slider.SetBinding("value", new DataBinding -{ - dataSourcePath = new PropertyPath(nameof(Settings.MasterVolume)), - bindingMode = BindingMode.TwoWay -}); -``` - -**Modes:** -- `ToTarget` - Data → UI (read-only, default) -- `ToSource` - UI → Data (write-only, rare) -- `TwoWay` - Data ↔ UI (input fields) - -### Runtime-Created Elements - -```csharp -var label = new Label(); -label.SetBinding("text", new DataBinding -{ - dataSourcePath = new PropertyPath(nameof(PlayerData.Name)) -}); -label.dataSource = m_PlayerData; -parentElement.Add(label); -``` - -## PanelRenderer with Bindings - -**Unity 6.6+ only** - `PanelRenderer` is a new UI Toolkit runtime component. - -**Use `PanelRenderer` instead of `UIDocument` for runtime UI with bindings.** - -`PanelRenderer` provides `RegisterUIReloadCallback` which ensures bindings are properly re-established if the UI reloads. - -### PanelRenderer Controller - -```csharp -using Unity.Properties; -using UnityEngine; -using UnityEngine.UIElements; - -public class StatsController : MonoBehaviour -{ - [SerializeField] private MyStats m_Stats; - private ScriptableObject m_LoadedData; - - private void Awake() - { - m_LoadedData = ScriptableObject.Instantiate(m_Stats); - } - - private void OnEnable() - { - GetComponent<PanelRenderer>().RegisterUIReloadCallback(OnUIReload); - } - - private void OnUIReload(PanelRenderer panelRenderer, VisualElement rootElement) - { - var hpLabel = rootElement.Q("hpLabel"); - var mpLabel = rootElement.Q("mpLabel"); - - rootElement.dataSource = m_LoadedData; - - hpLabel.SetBinding("text", new DataBinding - { - dataSourcePath = new PropertyPath(nameof(MyStats.HP)) - }); - - mpLabel.SetBinding("text", new DataBinding - { - dataSourcePath = new PropertyPath(nameof(MyStats.MP)) - }); - } -} -``` - -**Key benefits:** -- Callback handles UI reload events automatically -- Bindings re-established if UI is reloaded -- Cleaner than manual OnEnable setup -- Works with ScriptableObject data sources diff --git a/skills/using-unity/references/ui-uitk/references/uss-guide.md b/skills/using-unity/references/ui-uitk/references/uss-guide.md deleted file mode 100644 index 6bfeb58..0000000 --- a/skills/using-unity/references/ui-uitk/references/uss-guide.md +++ /dev/null @@ -1,138 +0,0 @@ -# USS Patterns and Examples - -## Table of Contents - -- [Design Tokens](#design-tokens) -- [Transitions](#transitions) -- [Pseudo-State Tinting](#pseudo-state-tinting) -- [Text Wrapping](#text-wrapping) -- [9-Slice Backgrounds](#9-slice-backgrounds) -- [Child vs Descendant Selectors](#child-vs-descendant-selectors) -- [Specificity](#specificity) - -## Design Tokens - -Use `:root` variables for repeated values: - -```uss -:root { - --spacing-sm: 8px; - --spacing-md: 16px; - --spacing-lg: 24px; - --color-primary: #4da3ff; - --color-bg-dark: #1a1a1a; - --color-text: #ffffff; -} - -.container { - padding: var(--spacing-md); - background-color: var(--color-bg-dark); - color: var(--color-text); -} - -.button { - padding: var(--spacing-sm) var(--spacing-md); - background-color: var(--color-primary); -} -``` - -## Transitions - -Define transition properties on the **base class**, not on `:hover`. Otherwise hover-out won't animate. - -```uss -/* CORRECT */ -.button { - background-color: #4da3ff; - transition-duration: 0.2s; -} -.button:hover { - background-color: #6db3ff; -} - -/* WRONG - transition on :hover won't animate out */ -.button { - background-color: #4da3ff; -} -.button:hover { - background-color: #6db3ff; - transition-duration: 0.2s; -} -``` - -## Pseudo-State Tinting - -Prefer tinting one image instead of creating multiple image variants: - -```uss -.button { - background-image: url("project://database/Assets/UI/Textures/button-bg.png"); -} - -.button:hover { - -unity-background-image-tint-color: rgba(255, 255, 255, 0.15); -} - -.button:active { - -unity-background-image-tint-color: rgba(0, 0, 0, 0.2); -} - -.button:disabled { - -unity-background-image-tint-color: rgba(128, 128, 128, 0.5); -} -``` - -## Text Wrapping - -Labels don't wrap by default. Enable wrapping explicitly: - -```uss -.description-text { - white-space: normal; - overflow: visible; -} -``` - -## 9-Slice Backgrounds - -For scalable backgrounds that stretch without distorting edges: - -```uss -.panel-background { - background-image: url("project://database/Assets/UI/Textures/panel-bg.png"); - -unity-slice-left: 12; - -unity-slice-top: 12; - -unity-slice-right: 12; - -unity-slice-bottom: 12; - -unity-slice-scale: 1; -} -``` - -Slice values define the non-stretched border regions in pixels. - -## Child vs Descendant Selectors - -Prefer child selectors for performance: - -```uss -/* BETTER - child selector */ -.panel > .header > .title { } - -/* AVOID - descendant selector (slower) */ -.panel .header .title { } -``` - -## Specificity - -More specific selectors override less specific ones. If your styles aren't applying, check for conflicting selectors: - -```uss -/* Less specific */ -.button { color: white; } - -/* More specific - wins */ -.panel .button { color: black; } - -/* Even more specific - wins */ -.panel > .content > .button { color: red; } -``` diff --git a/skills/using-unity/references/ui-uitk/ui-uitk.md b/skills/using-unity/references/ui-uitk/ui-uitk.md deleted file mode 100644 index 92c3a5e..0000000 --- a/skills/using-unity/references/ui-uitk/ui-uitk.md +++ /dev/null @@ -1,229 +0,0 @@ ---- -name: ui-uitk -description: Understands, edits, and generates Unity UI Toolkit UXML and USS with flex layouts. Use for requests involving UI Toolkit, UIElements, UIDocument, PanelSettings, custom elements, or UI runtime binding. ---- - -Understand existing Unity UI Toolkit code, make targeted edits, generate new UXML/USS files, Manipulators, and handle UI runtime binding. - -## References - -Read these as needed: -- [references/uss-guide.md](references/uss-guide.md) — USS patterns and examples -- [references/svg-icons.md](references/svg-icons.md) — SVG icon generation (only when generating icons) -- [references/common-issues.md](references/common-issues.md) — Common mistakes to avoid -- [references/ui-runtime-binding.md](references/ui-runtime-binding.md) — Patterns and guide to bind data to UI at runtime (only when requested or when bindings are involved) -- [references/painter2d.md](references/painter2d.md) — Painter2D API for custom visuals: gradients, shapes, arcs, procedural drawing (read this whenever gradients, custom shapes, progress rings, procedural drawing, or any visual beyond what USS can express is needed) -- [references/pointermanipulator-guide.md](references/pointermanipulator-guide.md) — Patterns and guide to create and use Manipulators (only when requested or when manipulators are involved). This helps with setting up drag and drop features or simple event handling for a Visual Element. -- [references/custom-elements.md](references/custom-elements.md) — Custom UI Element patterns and guide to create reusable components with UXML, USS, and C#. This helps with creating complex UI components for reuse across the project. - -Paths are relative to this skill's folder — read `references/uss-guide.md` directly. - -## Understanding - -When explaining UI structure, use this format: -``` -[ElementType] name="elementName" class="class1 class2" -├── [ChildType] name="childName" -│ └── [GrandchildType] -└── [ChildType] class="another-class" -``` - -## Editing - -**Common edit requests:** - -| Request | Action | -|---------|--------| -| "Change button color" | Edit USS selector for that button | -| "Add a label here" | Add element to UXML at specified location | -| "Make this bigger" | Edit width/height in USS | -| "Hide this element" | Add `display: none` to USS or remove from UXML | -| "Rename this element" | Update `name` attribute in UXML | - -**Don't over-edit:** -- Change only what's requested -- Preserve formatting and structure -- Don't "improve" unrelated code -- Don't add comments unless asked -- For targeted changes, prefer modifying specific elements or selectors over rewriting entire files — but use judgment; if a change touches most of the file, a rewrite may be cleaner -- Be careful not to accidentally drop existing elements, styles, or references when making edits -- **When editing USS**, focus on the properties and selectors relevant to the request — avoid unnecessary reorganization, but restructure if the change genuinely requires it - -## Validation - -There is no way to validate UXML or USS from outside the Editor — Unity parses these -files on import and reports problems in the Console. Write the files, then have the -user check the result. - -**Workflow:** - -1. Write the complete file to its target path in the project. Do not write partial or - draft content — a half-written UXML file is a parse error the moment the Editor - picks it up. -2. Ask the user to focus the Unity Editor. That triggers a reimport of the changed - assets. -3. Ask them to report anything in the Console. UXML parse errors name the file and - line; USS problems appear as warnings about unknown properties or selectors. -4. Fix what they report and repeat from step 1. - -**Because feedback costs a user round-trip, get it right the first time:** - -- Finish all files before asking the user to check, so one reimport covers everything - rather than one per file. -- Re-read `references/uss-guide.md` and `references/common-issues.md` before writing, - rather than after an error comes back. -- Watch for the mistakes that survive a parse but render wrong — those will not appear - in the Console at all, so the user has to eyeball the UI. `references/common-issues.md` - lists them. - -## Generation - -When creating new UI: - -**Generate only what is requested:** - -| Request | Output | -|---------|--------| -| USS only | `.uss` file only | -| UXML only | `.uxml` file only | -| UI screen / menu / panel | `.uss` + `.uxml` only | -| "with code" / "with logic" / "functional" | `.uss` + `.uxml` + `.cs` | - -**These do NOT imply C#:** -- "proper buttons" → well-styled Button elements -- "currency display" → a Label element -- "working UI" → valid UXML/USS that renders -- "inventory screen" → visual layout only -- "inventory system" / "equipment system" / "crafting system" → Ask: "Should items be draggable?" If yes, see `references/pointermanipulator-guide.md` for patterns - -**Generation workflow:** -1. **Analyze** — Determine exactly what files are needed. No extras. -2. **Search** — Find existing USS, UXML, assets. Don't assume paths. -3. **Follow project patterns** — Match folder structure and naming conventions. -4. **Reuse** — Check for shared stylesheets. Reuse if appropriate. -5. **Write USS first** — Verify against restrictions below. -6. **Write UXML** — Reference the USS, verify structure. -7. **Write the files out complete** — never partial content; see Validation above for - how errors come back and why one round of files beats several. -8. **Scene setup** — Assign PanelSettings if adding UI to scene. -9. **Data binding** — If requested, add C# script with runtime data binding patterns (see `references/ui-runtime-binding.md`). Generate the scriptable object asset if needed. Assign the asset to the UI element root in UXML or via datasource in C#. - -**Color, visibility, and specification rules:** -- **Ensure text is readable by default:** When choosing colors, ensure text contrasts with its background — but respect intentional low-contrast uses (disabled states, placeholder text, decorative elements). When using design tokens, check that text and background variables provide adequate contrast. -- **Honor exact values:** User-specified hex colors, pixel dimensions, spacing — use exactly as given. Do not approximate or substitute. - -**Styling / Theme** -When styling UI or adjusting theme make sure to not only apply to the elements directly in the current UXML but also to the core elements of UI Toolkit which are composed of several child elements usually. - -## Conventions - -**Follow project patterns first.** Search existing files before applying defaults. - -| Type | Convention | Good | Bad | -|------|------------|------|-----| -| `name` attribute | camelCase | `submitButton` | `submit-button` | -| `class` attribute / USS | kebab-case | `.submit-button` | `.submitButton` | -| File paths | Feature folders | `Assets/UI/Inventory/` | `Assets/Scripts/UI/` | - -**Output format:** -```uxml Filename.uxml -<ui:UXML>...</ui:UXML> -``` -```uss Filename.uss -.class { ... } -``` - -## USS Restrictions - -Unity's USS is a subset of CSS. These properties do NOT exist — NEVER use them: - -| NEVER Use | Use Instead | -|-----------|-------------| -| `border` shorthand | `border-width`, `border-color` separately | -| `gap` | `margin` on children | -| `z-index` | DOM order or parent nesting | -| `pointer-events` | `picking-mode` UXML attribute | -| `filter` | Not supported | -| `outline` | `border-*` properties | -| `box-shadow` | Nested elements or background image | -| `:first-child`, `:last-child`, `:nth-child` | Explicit classes | -| `[attribute]` selectors | Explicit classes | -| `transition-property: <value>` | Omit entirely, or `none`/`initial`/`inherit` only | -| `linear-gradient()`, `radial-gradient()` | Custom `VisualElement` with Painter2D (see `references/painter2d.md`) | - -**Inline styles:** NEVER use `style="..."` in UXML. All styling in USS only. - -**External URLs:** NEVER use `url()` with external paths. Only `url("project://database/Assets/...")`. - -**Prefer flexible layouts over hardcoded sizes:** -- Use `flex-grow`, `flex-shrink`, or `%` instead of fixed `width`/`height` values -- Let elements flow naturally and be constrained by their parent container -- Set explicit pixel sizes only on root containers or when a fixed size is truly required -- Child elements should adapt to available space rather than define their own dimensions - -## USS Brevity - -- No default values (`flex-direction: column` is default) -- No default fonts -- No redundant constraints (`width: 100px` doesn't need `min-width`/`max-width`) -- No overlapping properties (`flex: 1` already sets grow/shrink) -- Simplest selector that works -- Never duplicate selectors - -## UXML - -Every file must: -1. Declare namespace: `<ui:UXML xmlns:ui="UnityEngine.UIElements">` -2. Link stylesheet(s): `<ui:Style src="Screen.uss" />` -3. Have exactly one top-level container -4. **No `style="..."` attributes** — use USS only - -```uxml -<ui:UXML xmlns:ui="UnityEngine.UIElements"> - <ui:Style src="Panel.uss" /> - <ui:VisualElement name="root" class="panel"> - <!-- content --> - </ui:VisualElement> -</ui:UXML> -``` - -## Events and Interactivity -- Use Pointer Manipulators for event handling and interactivity on a VisualElement (see `references/pointermanipulator-guide.md`) -- If drag and drop is requested then write a pointer Manipulator and attach it to the relevant Visual Element in UXML or via C#. -- For simple click events, you can use the `clickable` manipulator in UXML -- For more advanced interactions, create use more traditional event callbacks in C# and attach them to elements as needed - -**For inventory and crafting systems:** -- When users request an "inventory system", "equipment system", or "crafting system", ask explicitly: "Should players be able to drag and drop items?" -- If yes, read `references/pointermanipulator-guide.md` for inventory/crafting-specific patterns -- If no or unclear, create static layout only - -## Assets - -**Do NOT reference `UnityDefaultRuntimeTheme.tss`** or Unity's built-in theme icons. - -**Icon priority:** -1. Reuse existing project icons -2. Generate SVG (see `references/svg-icons.md`) -3. Image generators (last resort) - -**Reference format:** -```uss -background-image: url("project://database/Assets/UI/Textures/icon.png"); -``` - -## Scene Setup - -**PanelSettings is required** — UI won't render without it. - -1. Search for existing PanelSettings asset -2. If none, create generic: `Assets/UI/PanelSettings.asset` -3. Assign to UIDocument's `Panel Settings` field - -Skip for Editor UI (EditorWindow, PropertyDrawer). - -## C# (Only When Requested) - -- Style via USS classes (`AddToClassList()`) — never use `element.style.*` as inline styles have higher specificity than USS selectors, making them impossible to override via stylesheets, and add per-element memory overhead -- UITK uses TextCore text assets — use `FontAsset`, `TextStyleSheet`, and `TextSettings`, not their TextMeshPro equivalents (`TMP_FontAsset`, etc.) -- Place scripts in same folder as UXML/USS diff --git a/skills/using-unity/references/ui/ui.md b/skills/using-unity/references/ui/ui.md deleted file mode 100644 index 46b3c57..0000000 --- a/skills/using-unity/references/ui/ui.md +++ /dev/null @@ -1,142 +0,0 @@ ---- -name: ui -description: Routes Unity UI requests to the right framework skill (UI Toolkit, uGUI, or IMGUI) and answers UI comparison questions. Use for menus, HUDs, panels, or editor UI when the request doesn't name a framework. Consult before writing any UI code. ---- - -Determine the appropriate UI system for the project and route to the correct specialized skill. - -## When to Route vs Answer Directly - -**Route to a specialized skill when:** -- User wants to understand, edit, or generate specific UI elements -- User references specific files or UI objects -- User asks for UI changes or creation - -**Answer directly (without routing) when:** -- User asks comparative/educational questions ("What's the difference between UI Toolkit and uGUI?") -- User asks about UI system capabilities or recommendations ("Should I use UITK or uGUI for mobile?") -- User needs conceptual explanation of Unity UI architecture - -## Routing Logic - -**Step 1: Check for explicit file references or keywords:** - -| User mentions | Route to | -|---------------|----------| -| `.uxml` or `.uss` files (including in `/Editor/`) | `ui-uitk` | -| "UI Toolkit", "UITK", "UIElements", "CreateGUI" | `ui-uitk` | -| Canvas prefabs/objects, `.prefab` with UI | `ui-ugui` | -| "uGUI", "Canvas", "RectTransform", "legacy UI" | `ui-ugui` | -| "IMGUI", "OnGUI", "OnInspectorGUI", "immediate mode" | `ui-imgui` | -| Figma URL (`figma.com/design/...`), "Figma", "import from Figma" | Not available — see below | - -**For editor-related requests (EditorWindow, custom inspector, PropertyDrawer):** -- If no explicit UI system mentioned → **Go to Step 2** to detect project's editor UI system -- If no existing pattern is detected, default to `ui-uitk` for new editor UI -- Only use `ui-imgui` if project exclusively uses IMGUI or user explicitly requests it - -If explicit file or keywords found, activate the corresponding skill immediately. - -**Step 2: If ambiguous, detect from project:** - -Search the project to determine which UI system is in use: - -| Look for | Indicates | -|----------|-----------| -| `.uxml` or `.uss` files (including in `/Editor/`) | UI Toolkit (runtime or editor) | -| `UIDocument` components in scenes | UI Toolkit (runtime) | -| Editor scripts with `CreateGUI()` method | UI Toolkit (editor) | -| `Canvas` in scenes/prefabs | uGUI | -| `RectTransform` heavy usage | uGUI | -| Editor scripts with `OnGUI()` or `OnInspectorGUI()` | IMGUI (legacy editor) | - -**Step 3: If still unclear, ask or default:** - -- For existing projects: detect and follow whichever framework is already in use (Step 2) -- For new projects with no UI yet: ask the user which framework they prefer (UI Toolkit vs uGUI), briefly explaining that UI Toolkit is modern/CSS-like while uGUI is Canvas-based/mature -- For new runtime/game UI where the user has no preference: default to uGUI (`ui-ugui`) -- When the user mentions mobile/performance constraints or older Unity versions (pre-6.0): bias toward uGUI (`ui-ugui`) - -## Request Types - -Specialized skills handle three types of requests: - -| Type | Examples | -|------|----------| -| **Understanding** | "What does this button do?", "How is this laid out?", "Explain this UI" | -| **Editing** | "Change this color", "Add a label here", "Fix this layout" | -| **Generation** | "Create a menu", "Make an inventory screen", "Build a settings panel" | - -Route all types to the appropriate specialized skill based on the UI system. - -## Available Sub-Skills - -### UI Toolkit — `ui-uitk` -- For Unity 6.0+ projects using UI Toolkit (runtime game UI and editor tools) -- **Understands**, **edits**, and **generates** `.uxml` and `.uss` files -- Modern, CSS-like styling approach -- Preferred for new editor windows (CreateGUI) and existing UI Toolkit projects - -### uGUI — `ui-ugui` -- For projects using Unity's Canvas-based UI system -- **Understands**, **edits**, and **generates** Canvas hierarchies -- Uses Layout Groups for responsive design -- Default for new runtime/game UI when the user has no framework preference - -### IMGUI — `ui-imgui` -- For legacy editor tools using OnGUI/immediate mode -- Only use when project has existing IMGUI editor code or user explicitly requests IMGUI -- **Understands**, **edits**, and **generates** EditorWindow, inspectors, PropertyDrawers built with OnGUI -- Not for runtime game UI — for new editor tools, use UI Toolkit unless the project already uses IMGUI exclusively - -### Figma design import — not available here - -Importing a Figma design requires Unity's Figma integration service, which only exists -inside Unity AI Assistant. There is no client-side equivalent, so do not promise it. - -If the user brings a Figma URL, say the automated import is not available here and offer -the alternative: ask them to describe or screenshot the screen, then build it with the -appropriate framework skill above. - -## Common Guidelines (All UI Systems) - -### Scope Discipline - -**Do only what is requested:** -- Question → answer without making changes -- Targeted edit → modify only what's specified -- Generation → create only requested files -- Don't proactively add scripts unless explicitly asked - -**These do NOT imply scripts:** -- "proper buttons" → well-styled buttons -- "working UI" → valid UI that renders -- "menu screen" → visual layout only - -### Conventions - -**Follow project patterns first.** Search existing files before applying defaults. - -| Type | Convention | -|------|------------| -| Element names | Follow project patterns, or camelCase | -| File organization | Match existing project structure | - -### Workflow - -1. **Determine UI system** — Use routing logic above - - For Figma requests, tell the user the automated import is not available here, then - work from their description or screenshot and continue with framework detection -2. **Activate specialized skill** — Route to `ui-uitk`, `ui-ugui`, or `ui-imgui` -3. **Skill handles request** — Understanding, editing, or generation as appropriate - -## Handling Mixed Projects - -Many Unity projects use multiple UI systems simultaneously (e.g., UI Toolkit for runtime game UI plus editor tools). When you detect multiple systems: - -- **For runtime UI requests** (menus, HUDs, game screens) → Route to whichever runtime system (UITK or uGUI) is already in use -- **For editor tool requests** (custom inspectors, editor windows): - - **Prefer UI Toolkit** (CreateGUI) for new editor UI — it's the modern approach - - Only use IMGUI if the project's existing editor tools use IMGUI exclusively, or user explicitly requests IMGUI - - Check for existing editor `.uxml` files to confirm UITK usage -- **If creating new runtime UI in a mixed project** → Match the pattern used by similar existing UI; if there is no similar existing UI and the user has no preference, use uGUI diff --git a/skills/using-unity/references/unity-pipeline/SECURITY.md b/skills/using-unity/references/unity-pipeline/SECURITY.md index ad74dc0..40e6817 100644 --- a/skills/using-unity/references/unity-pipeline/SECURITY.md +++ b/skills/using-unity/references/unity-pipeline/SECURITY.md @@ -1,17 +1,17 @@ # Security notes: unity-pipeline -This skill has the agent run C# inside a Unity Editor or development Player the user already has running, through `unity command script eval`, `script eval_file`, `script run` and `script.methodreload reload`. Automated skill scanners flag that as a powerful capability. It is intentional, and it is limited by the safeguards below. +This skill has the agent run C# inside a Unity Editor or development Player the user already has running, through `unity command script eval`, `script run` and `script.methodreload reload`. Automated skill scanners flag that as a powerful capability. It is intentional, and it is limited by the safeguards below. ## Accepted risks | Risk | Capability | Why it is accepted | |---|---|---| -| `SEC_POWER_CAP` | Runs C# in the user's running Editor or development Player through `unity command script eval`, `script eval_file`, `script run` and `script.methodreload reload` | It only reaches an instance the user started, with the Pipeline package they installed, so it grants nothing they couldn't do in that Editor themselves. No code fetched from a remote source is run. The skill steers ad-hoc code into versioned project files run with `script run`, and keeps `script eval` for one-liners. | +| `SEC_POWER_CAP` | Runs C# in the user's running Editor or development Player through `unity command script eval`, `script run` and `script.methodreload reload` | It only reaches an instance the user started, with the Pipeline package they installed, so it grants nothing they couldn't do in that Editor themselves. No code fetched from a remote source is run. The skill steers ad-hoc code into versioned project files run with `script run`, and keeps `script eval` for one-liners. | ## Mitigations - **Only the user's own instances.** Commands go to an Editor or development Player the user is running with the Pipeline package installed. Runtime commands need a development build; release Players have no Pipeline server. - **No remote code.** The agent runs C# it writes for the user's task. Nothing downloaded from outside is executed. - **Code lives in reviewable files.** Bulk work goes into scripts on disk run with `script run`, so the user can read and version what ran. `script eval` is reserved for short one-liners. -- **Compile-only check.** `script run --dry_run true` reports diagnostics without loading or running anything. +- **Compile-only check.** `script run --dry-run` reports diagnostics without loading or running anything. - **Named commands first.** When a dedicated `unity command` covers a step, the skill uses it instead of running C#. diff --git a/skills/using-unity/references/unity-pipeline/unity-pipeline.md b/skills/using-unity/references/unity-pipeline/unity-pipeline.md index f2ab1d4..9ca4d64 100644 --- a/skills/using-unity/references/unity-pipeline/unity-pipeline.md +++ b/skills/using-unity/references/unity-pipeline/unity-pipeline.md @@ -1,6 +1,6 @@ --- name: unity-pipeline -description: Control a Unity Editor or Player via the unity-pipeline package. Compile, run tests, eval, method-reload code, enter Play Mode, capture screenshots. +description: Controls a Unity Editor or dev Player through the com.unity.pipeline package to compile, run tests, evaluate C#, method-reload code, enter Play Mode and capture screenshots. Make sure to use this skill when the user asks to drive, test, debug or inspect a running Unity Editor or Player from the command line. --- # Unity Pipeline (agent control) @@ -10,11 +10,36 @@ groups, `unity command <group>` one group's commands, and `--query <term>` filte description or tag. Two servers exist: **Editor** (`7800-7849`, auto-starts with the editor) and **Runtime** (`7900-7949`, only in a dev Player build). +## Targeting the Editor + +**Always pass `--project-path <project>`, or run `unity` from inside the project folder.** A +project folder holds exactly one Editor, so this is unambiguous, needs no other flag, and reads the +Editor's port and token straight from the project, with no process scan. An MPPM clone is its own +project: `--project-path <mainProject>/Library/VP/<vpId>`. + +Don't use `--port`, `--pid` or `--instance` unless the user asks for them. Without +`--project-path` they search every running Editor: on Unity 6 (6000.x) that is a scan of every +process, a second or more on each call; only Unity 7 Editors answer it without a scan. The CLI +warns on stderr when a call had to scan. + +## Before you start + +- If the package is not installed, install it first ([1. Install & verify](#1-install--verify)). +- Before any other workflow or diagnosis, open and read the [Topic map](#topic-map) pages for your + task, and name the files you read. Your training knowledge about Unity and this package may be + out of date, incorrect, or for the wrong version. +- Read only `.md` files in the installed package's `Documentation~` folder, or the live pages for + its version, as the [Topic map](#topic-map) describes. +- Create a restore point you can roll back to if your changes fail, such as a git commit or stash. +- Do only what's asked. Don't change unrelated assets or files. Avoid long explanations. +- Never leave verification code in the user's script. Never build logging or detection they didn't + ask for. + ## 1. Install & verify ```bash unity pipeline install # install into current project (or --project-path) -unity pipeline list # confirm the editor instance + server are reachable +unity pipeline editors # list Editor instances and their Pipeline status unity status --until-ready # wait until the editor server is ready unity command editor status # confirm the editor server answers ``` @@ -28,8 +53,8 @@ persists, ask the user to switch to the Unity Editor window, then re-run `unity This is the core agent workflow: keep the editor alive, change code, recompile, test. ```bash -# 1. Keep the editor ticking even when unfocused/minimized. REQUIRED before headless work — -# Unity otherwise throttles or stalls update/compile when it isn't the active app. +# 1. Keep the editor ticking when unfocused or minimized; otherwise Unity throttles update and +# compile. It is on by default, but a session that set it explicitly keeps its own value. unity command editor set_auto_tick --enabled true # 2. Edit C# source files on disk normally. @@ -38,7 +63,9 @@ unity command editor set_auto_tick --enabled true unity command script recompile unity command script recompile_status # repeat until "completed" or "up_to_date" # Tolerate connection errors while the domain reload is in flight — that is expected. -# If script recompile_status reports failed=true, read its "errors" array and fix before testing. +# If script recompile_status reports failed=true, read its "errors" array. Fix errors in code +# you wrote; for errors in the user's code, report them and ask before editing. Tests run on a +# failed compile use the last assemblies that built, so their results don't cover the change. # 4. (Optional) List available tests without running them. unity command test list --mode editor # mode: all | editor | playmode @@ -47,9 +74,11 @@ unity command test list --mode editor # mode: all | editor | playmode unity command test run --mode editor --filter MyFixture.MyTest ``` -`filter-type`: `testName` | `assembly` | `category`. For long runs use `--async-tests true` and -poll `unity command test status` (abort with `test cancel`). When a selected test *fails*, `test run` -may return an opaque result: re-run a narrower `--filter`, or inspect the Test Runner / logs. +`test run` modes: `editor` (default) | `playmode` | `all` (both need `--async-tests true`). `filter-type`: +`testName` | `assembly` | `category`. Use `--async-tests true` and poll `unity command test status` for long +runs and any run that may reload the domain (a reload drops a synchronous run's request; abort with `test cancel`). +A synchronous run returns one record per test, failures included, with its message and stack trace. For an +async run, `unity command test status --detail failures` returns only the failed tests' results. **Reading exit codes.** They separate "rewrite the invocation" from "the Editor failed", which is the distinction this loop depends on: @@ -57,37 +86,37 @@ is the distinction this loop depends on: | Exit | Meaning | What to do | |------|---------|------------| | `2` | Bad arguments — a misspelled flag, a wrong type, too many positionals. Nothing ran. | Fix the command line and retry. The error names the problem and often suggests the right flag. | -| `6` | The command ran and failed, or no Editor could be reached. | Read the error. If it says no Pipeline instance was found, the Editor isn't reachable: wait with `unity status --until-ready` (or check `unity pipeline list` for Safe Mode), then retry. Otherwise retrying the same invocation will not help. | +| `6` | The command ran and failed, or no Editor could be reached. | Read the error. If it says no Pipeline instance was found, the Editor isn't reachable: wait with `unity status --until-ready` (or check `unity pipeline editors` for Safe Mode), then retry. Otherwise retrying the same invocation will not help. | Do not retry an exit 2 unchanged, and do not rewrite a command line on an exit 6. ## 3. Runtime method reload -Change gameplay code in a **running** game with no domain reload. The game must be live: -enter Editor Play Mode (`unity command editor.playmode start`) or run a dev Player. The runtime Pipeline driver (enabled via Project Settings > Pipeline > Runtime) auto-discovers tagged methods on `Awake` (no manual -registration). Mono only — Editor Play Mode and Mono desktop dev builds, not IL2CPP. The token -is auto-injected for local requests. - -### `script.methodreload reload` - -Edit the method body directly; no separate file, no boilerplate. - -1. **Before entering Play Mode**, tag the method `[MethodReload]` on the MonoBehaviour and recompile. - The reload hook is compiled into the method, so tagging it while the game runs has no effect: - exit Play Mode, recompile, and enter it again. +Change gameplay code in a **running** game with no domain reload. The game must be live: enter +Editor Play Mode (`unity command editor.playmode start`) or run a dev Player with the runtime +Pipeline driver enabled (Project Settings > Pipeline > Runtime). Two backends: + +- `script.methodreload reload` loads a compiled assembly: Editor Play Mode and Mono desktop dev + builds only. The reloaded body may touch only **public** members of its type. +- `script.methodreload reload_editor` and `reload_player` run the edited IL through an + interpreter, in the Editor or in connected dev Players, **including IL2CPP**. They accept a C# + subset, and `reload_player` needs the Editor running. + +1. **Before entering Play Mode**, tag the method `[MethodReload]` (`using Unity.Pipeline.MethodReload;`, + assembly `Unity.Pipeline.Attributes`, auto-referenced) and recompile. The reload hook is + compiled into the method, so tagging it while the game runs has no effect: exit Play Mode, + recompile, and enter it again. A tagged method is `public`, instance or static, and returns + `void` or `IEnumerator` (a running coroutine keeps its old body; new `StartCoroutine` calls get + the new one). 2. With the game running, edit the method body on disk. 3. Apply (re-run to iterate): ```bash unity command script.methodreload reload --filename Assets/Spinner.cs + unity command script.methodreload reload_player Assets/Scripts/Player.cs # device, IL2CPP too ``` - Add `--pdb` to debug it: it emits a portable PDB mapped to your source so breakpoints bind - (attach the IDE + enable Editor Attaching; compiles unoptimized). Without it, no symbols. - -Constraints: `void` instance methods only; **public** members only. + `--pdb` on `reload` emits a source-mapped PDB so IDE breakpoints bind (compiles unoptimized). -`unity command script.methodreload status` shows active overrides. `reload` options: `--timeout -<seconds>` (default 60; the CLI's `--timeout` is the command's own), `--assembly-dir <dir>` (persist -DLLs instead of in-memory); `script.methodreload cleanup --assembly-dir <dir>` clears old DLLs. +`unity command script.methodreload status` shows active overrides. ## 4. Bulk construction: `script run` (the builder pattern) @@ -102,7 +131,7 @@ a 15–20s recompile. # 2. Run it — relative paths resolve against the project root (the parent of Assets/): unity command script run --file AgentScripts/Build.cs --entry Build.All # 3. Iterate: edit the file, re-run. Useful extras: -unity command script run --file AgentScripts/Build.cs --dry-run true # compile-only check: diagnostics, nothing loaded or executed +unity command script run --file AgentScripts/Build.cs --dry-run # compile-only check: diagnostics, nothing loaded or executed unity command script run --file AgentScripts/Build.cs --entry Build.All --args '[3, "Green"]' ``` @@ -141,132 +170,80 @@ unity command script eval --caller plugin --skill unity-pipeline "return UnityEd - `await Wait.Until(() => condition)` waits without blocking the Editor; `Wait.For(asyncOperation)` and `Wait.ForImport(assetPath)` cover operations and imports. Submit a long wait with `--detach`, then `unity job wait <job-id>`. -- A failed eval exits 6 with an `errorCode`: `COMPILATION_ERROR` (each error with its line and - column), `RUNTIME_EXCEPTION` (exception and stack trace), `TIMEOUT` or `INVALID_COMMAND_ARGS`. -- `script eval_file` is deprecated; use `script eval --file`. +- A failed eval exits 6 with an `errorCode`: -## 6. Play Mode vs. Multiplayer Play Mode (MPPM) scenarios + | `errorCode` | Cause | Resolution | + |-------------|-------|------------| + | `COMPILATION_ERROR` | The code doesn't compile; each error has its line and column. | Fix the code at those lines; `--auto-import` adds missing usings. | + | `RUNTIME_EXCEPTION` | The code threw; the result has the exception and stack trace. | Fix the failing line the stack trace names. | + | `TIMEOUT` | The code ran past `--timeout`. | Raise `--timeout`, or submit with `--detach` and `unity job wait`. | + | `INVALID_COMMAND_ARGS` | The arguments are invalid or conflict. | Fix the command line. | -These are two different things — do not conflate them. +## 6. Authoring scenes, GameObjects, prefabs and assets -### Single-player: normal Play Mode (main Editor only) +The `scene`, `gameobject`, `component`, `prefab` and `asset` groups edit content directly, with no +script. Objects are addressed by a handle (globalId, path, guid, instanceId or hierarchy path), and +each result returns one to chain into the next call. Scene edits are undoable and blocked in Play +Mode. For many objects, use `gameobject create_many` or a `script run` builder (§4). ```bash -unity command editor.playmode start # enter Play Mode -unity command editor.playmode pause # toggle pause -unity command editor.playmode stop # exit Play Mode +unity command scene get_hierarchy # the active scene's objects +unity command gameobject create --name Enemy --primitive cube +unity command component add --target <handle> --type Rigidbody +unity command component set_properties --target <handle> --type Rigidbody --properties '{"m_Mass":2}' +unity command prefab create --source <handle> --path Prefabs/Enemy +unity command scene save ``` -`editor.playmode start` runs the main Editor's **open scene** in Play Mode: **one** instance, never -MPPM virtual players, even if configured. Use it for single-instance testing and method reload. - -### Multiplayer: Play Mode Scenarios (main Editor + virtual players) - -A **Play Mode Scenario** is an asset (an `OrchestratedScenario`, e.g. -`Assets/Settings/PlayMode/2Players.asset`) describing the main Editor plus one or more virtual -players. Each virtual player (clone) is a **separate Unity project** at -`<project>/Library/VP/<vpId>` with its **own Library, port, and Pipeline server** — not a second -window of the main Editor. Run a scenario with the scenario commands (they drive MPPM's -`PlayModeScenarioManager`, which enters Play Mode itself), never with `editor.playmode start`, -which fights MPPM's play-mode guard: +## 7. Play Mode and multiplayer ```bash -unity command editor.playmode list_scenarios # discover scenario assets -unity command editor.playmode list_players # players the active scenario declares -unity command editor.playmode set_active_scenario --path Assets/Settings/PlayMode/2Players.asset -unity command editor.playmode start_scenario # run the active scenario -unity command editor.playmode get_scenario_status # live scenario + play-mode state -unity command editor.playmode stop_scenario # stop it +unity command editor.playmode start # enter Play Mode (also pause, stop) ``` -Authoring the asset (Edit Mode): +`editor.playmode start` runs the main Editor's open scene: **one** instance, never Multiplayer Play +Mode (MPPM) virtual players, even if configured. -```bash -unity command editor.playmode create_scenario --name MyScenario # auto-adds the Main Editor player -unity command editor.playmode add_player --path Assets/Settings/PlayMode/MyScenario.asset --type clone --name "Player 2" -unity command editor.playmode remove_player --id <playerId> --path Assets/Settings/PlayMode/MyScenario.asset --confirm true # id: GUID on 6000.5+, player name on 6000.3/6000.4 -``` - -MPPM has four player slots, and slot 0 (`Player 1`) is always the Main Editor. A scenario therefore -holds at most **3 clones** (`Player 2`–`Player 4`): a 4-player scenario is the Main Editor plus 3 clones, -and a fourth clone is refused. For more players, add built players with `--type local`. - -The `editor.playmode` scenario commands need **Unity 6000.3+** *and* the `com.unity.multiplayer.playmode` -package. Without both they are compiled out and calling one fails as an unknown command, so run -`unity command editor.playmode` and check that `start_scenario` and the other scenario commands are listed -before using them. The group itself always exists: `editor.playmode list_instances` needs neither -and always works. You may only `editor.playmode set_active_scenario` while state is **Idle**. - -Player editors launch **asynchronously**, so after `editor.playmode start_scenario` poll -`editor.playmode get_scenario_status`. Its `players` array has one entry per player the scenario declares — not -MPPM's fixed four slots — and each entry carries both `state` (`NotLaunched` / `Launching` / -`Launched` / `UnexpectedlyStopped`) and, once that player's Editor is up, `reachable: true` with the -`port` and `projectPath` you need to drive it. Wait for `reachable`, then address it with -`--project-path`. Watch `state` to tell a slow launch (`Launching`) from a dead one -(`UnexpectedlyStopped`) — a missing descriptor alone cannot distinguish those. - -### Discovering and driving the clones - -The CLI folds a project's own clones into its main Editor, so a running scenario adds no -ambiguity by itself. But with another Unity project open, `unity command` with no `--project-path` -picks the Editor whose project contains the current directory (and fails as ambiguous outside -both). When more than one project is open, pass `--project-path <mainProject>` to the main Editor -commands above. Each clone runs its own server, so address one by its project directory: +**MPPM scenarios.** Run a scenario with the scenario commands, never with `editor.playmode start`, +which fights MPPM's play-mode guard: ```bash -# List every running instance (main + clones): role, port, pid, vpId, projectPath -unity command editor.playmode list_instances - -# Talk to a clone directly, using the projectPath that listed it -unity command --project-path <mainProject>/Library/VP/<vpId> editor status -# Each clone is its own Editor: keep it ticking before running tests on it -unity command --project-path <mainProject>/Library/VP/<vpId> editor set_auto_tick --enabled true -unity command --project-path <mainProject>/Library/VP/<vpId> test run --mode playmode +unity command editor.playmode list_scenarios +unity command editor.playmode set_active_scenario --path Assets/Settings/PlayMode/2Players.asset # only while Idle +unity command editor.playmode start_scenario +unity command editor.playmode get_scenario_status # poll: players launch asynchronously +unity command editor.playmode stop_scenario ``` -`unity pipeline list` also reports clones, named by player ("Player 2") against the project they're -playing. There is no forwarding command — talk to the clone. That way you get its full command -surface and its own status, and nothing queues behind the main Editor. - -### Multiplayer Roles (client / server stripping) - -Multiplayer Roles decide what is stripped from a client or a server: the Editor runs as one role in -Play Mode, and each GameObject or component is kept for some roles and stripped from the others. -Use the `multiplayer.role` commands rather than reflecting over `EditorMultiplayerRolesManager` in -`script eval`: - -```bash -unity command settings.multiplayer_roles get # enabled? safety checks, server stripping -unity command settings.multiplayer_roles set --settings '{"enabled":true}' --confirm true # nothing is stripped until roles are enabled -unity command multiplayer.role get_active # Editor role, and whether roles are enabled -unity command multiplayer.role set_active --role server # role the Editor plays as (Edit Mode only) -unity command multiplayer.role set_game_object --target <go> --role server # the GameObject -unity command multiplayer.role set_component --target <go> --type AudioSource --role client # one of its components -unity command multiplayer.role set_component --target <component handle> --role client # a component by handle -unity command multiplayer.role set_build --role server # role the active build profile builds for -``` +- They need Unity 6000.3+ and the `com.unity.multiplayer.playmode` package; otherwise they are + compiled out. Run `unity command editor.playmode` and check `start_scenario` is listed first. +- Each virtual player (clone) is a **separate Unity project** at `<project>/Library/VP/<vpId>` with + its own server. Wait for its `get_scenario_status` entry to show `reachable: true` (`Launching` + is slow, `UnexpectedlyStopped` is dead), then address it with that entry's `projectPath`. There + is no forwarding command: set auto tick and run tests on the clone itself. + ```bash + unity command --project-path <mainProject>/Library/VP/<vpId> test run --mode playmode --async-tests true + unity command --project-path <mainProject>/Library/VP/<vpId> test status # repeat until done + ``` -`role` is `client`, `server` or `client_and_server`. The group needs **Unity 6000.6+**; on older -Editors it is compiled out, so run `unity command multiplayer.role` to check it is listed. +**Multiplayer Roles** (client/server stripping, Unity 6000.6+). Nothing is stripped until roles are +enabled with `settings.multiplayer_roles set`. Assign roles with the `multiplayer.role` commands, +not by reflecting over `EditorMultiplayerRolesManager` in `script eval`; run +`unity command multiplayer.role` to check the group is listed. -## 7. Screen capture (Editor) +## 8. Screen capture (Editor) Capture a view to a PNG to check a visual result. ```bash unity command capture game_view --output-path Screenshots/hud.png # what the Game window shows, incl. overlay UI unity command capture scene_view --max-resolution 512 # the scene only (camera render), inline, longest edge capped -unity command capture scene_view --source screen --output-path Screenshots/scene.png # the Scene window with grid, gizmos, toolbars unity command capture editor_window --window Inspector --output-path Screenshots/inspector.png # any open Editor window ``` -Without `--output-path` the image comes back inline (base64); `--include-inline-image true` gives -both. A relative path resolves from the project root (no `.meta` outside `Assets/`). `game_view` -opens a Game view if none is showing, in batchmode too. `game_view --source camera --camera <name>` -renders one camera; overlay UI is drawn on URP/HDRP (`--overlay auto|true|false`), not on Built-in. -`editor_window` and `scene_view --source screen` briefly front a background tab and don't work in -batchmode. `capture screenshot` is deprecated. On 6000.7+, `capture editor_element` / -`runtime_element` capture one UI Toolkit element by `--selector`. +Without `--output-path` the image comes back inline (base64). A relative path resolves from the +project root. `editor_window` and `scene_view --source screen` briefly front a background tab and +don't work in batchmode. ## Gotchas @@ -274,6 +251,8 @@ batchmode. `capture screenshot` is deprecated. On 6000.7+, `capture editor_eleme thread until dismissed. If a command runs long, check `unity command editor status` (answers instantly even when blocked); `status: "blocked_by_dialog"` means stop retrying and tell the human what's blocking (its `dialog.title`/`message`/`buttons`) — it can't be clicked over CLI. + Some dialogs (`EditorUtility.DisplayDialog`) aren't detected yet: `editor status` itself then + times out. Treat that as the same case and ask the human to look at the Editor. - **Player-only commands need a dev Player.** `console write`, `runtime set_time_scale`, `runtime status`, etc. hit the Runtime server, which does not run in the Editor. - **Target a specific instance** when more than one is running: `--project-path <path>` selects an @@ -286,10 +265,11 @@ batchmode. `capture screenshot` is deprecated. On 6000.7+, `capture editor_eleme unity command console status # groundTruth.consoleErrors must be 0, compilationFailed false unity command console get --level error # read any errors it reports ``` -2. If you changed runtime behaviour, enter Play Mode (`unity command editor.playmode start`), exercise - the change, and read back the `Debug.Log` lines you added with `unity command console get`. Confirm - they show the fix works, then stop Play Mode and remove those lines unless the user wants them kept. -3. If the fix doesn't work, go back and reread the relevant [Topic map](#topic-map) pages before you +2. If you fixed or suspect a runtime fault, enter Play Mode once (`unity command editor.playmode start`), + check the behavior with `unity command script eval`, then stop Play Mode. Add no logging and take + no screenshots to do this. +3. Otherwise, with zero errors, stop there unless the user asked for proof that the change works. +4. If the fix doesn't work, go back and reread the relevant [Topic map](#topic-map) pages before you try again, rather than retrying from memory. ## Final report @@ -304,22 +284,27 @@ End with a short report to the user: ## Topic map -The Pipeline package ships its documentation in its `Documentation~` folder. For a registry install -that is `<project>/Library/PackageCache/com.unity.pipeline@*/Documentation~/`; the same pages are -published at `https://docs.unity3d.com/Packages/com.unity.pipeline@<VERSION>/`. Only read what you need. +The Pipeline package ships its documentation in its `Documentation~` folder: for a registry install +`<project>/Library/PackageCache/com.unity.pipeline@*/Documentation~/`, for a local or embedded +package the folder next to its `package.json`. The same pages are published at +`https://docs.unity3d.com/Packages/com.unity.pipeline@<VERSION>/`. Only read what you need. Prefer the local copy: it matches the installed package. For the live pages, fetch the exact URL -rather than searching; `<VERSION>` is the major.minor of `com.unity.pipeline` in -`Packages/packages-lock.json`, e.g. `@0.9`. +rather than searching, e.g. +`https://docs.unity3d.com/Packages/com.unity.pipeline@<VERSION>/connectivity.md`, where +`<VERSION>` is the major.minor of `com.unity.pipeline` in `Packages/packages-lock.json`, e.g. `@1.0`. | Topic | Page | |-------|------| | Connecting to an Editor or Player, ports, `--project-path` | `connectivity.md` | | Dev Player and Runtime server setup | `runtime-setup.md` | -| Method reload (`[MethodReload]`, `script.methodreload`) | `method-reload.md` | +| Method reload (`[MethodReload]`, `script.methodreload`, both backends) | `method-reload.md` | | `script run`, `script eval`, `script recompile` | `commands/scripts.md` | | Compiling and running tests | `commands/build-and-compilation.md` | | `editor status`, `editor set_auto_tick`, modal dialogs | `commands/editor-lifecycle-and-observability.md` | +| Scenes, GameObjects and components, prefabs, assets | `commands/scenes.md`, `commands/gameobjects-and-components.md`, `commands/prefabs.md`, `commands/assets-and-files.md` | | Play Mode scenarios, virtual players, clones | `commands/multiplayer-play-mode.md` | +| Multiplayer Roles | `commands/multiplayer-roles.md` | +| Waiting on a condition server-side (`job wait`) | `commands/wait.md` | | Screen capture | `commands/capture.md` | | `console get` / `console status`, Runtime commands | `commands/runtime.md` | diff --git a/skills/using-unity/references/urp-postprocessing/SECURITY.md b/skills/using-unity/references/urp-postprocessing/SECURITY.md index 6931d8c..9e82b61 100644 --- a/skills/using-unity/references/urp-postprocessing/SECURITY.md +++ b/skills/using-unity/references/urp-postprocessing/SECURITY.md @@ -12,5 +12,5 @@ This skill has the agent run C# inside the user's open Unity Editor through `uni - **Only the user's own Editor.** `unity command script eval` talks to the Editor open on this machine. It can't reach another machine or another user's Editor. - **Capability gate.** `script eval` is only available when the project's Pipeline package provides it. -- **No remote code.** The agent runs C# it writes from this skill's own recipes. Nothing downloaded from outside is executed. +- **No remote code.** The agent runs C# it writes from this skill's own recipes. The skill never tells it to download or run code from outside. - **Named commands first.** When a dedicated `unity command` covers a step, the skill uses it instead of `script eval`. diff --git a/skills/using-unity/references/urp-postprocessing/references/code-templates.md b/skills/using-unity/references/urp-postprocessing/references/code-templates.md index 30451db..e6066d1 100644 --- a/skills/using-unity/references/urp-postprocessing/references/code-templates.md +++ b/skills/using-unity/references/urp-postprocessing/references/code-templates.md @@ -1,7 +1,14 @@ ## Code Templates +### Contents + +- [Creating a Global Volume with Effects](#creating-a-global-volume-with-effects) +- [Enabling Post-Processing on Camera](#enabling-post-processing-on-camera) +- [Modifying an Existing Volume Profile](#modifying-an-existing-volume-profile) +- [Making a change undoable through `script eval`](#making-a-change-undoable-through-script-eval) + Each template is a snippet to run through the Editor's `script eval` command. Hard stops `throw`, -so the eval fails loudly; anything the caller needs to read is `return`ed. +so `script eval` fails loudly; anything the caller needs to read is `return`ed. **`script eval` compiles a statement block, not a file.** `using` directives are rejected there — the compiler reads `using UnityEngine;` as a resource-disposal statement and fails. So these diff --git a/skills/using-unity/references/urp-postprocessing/urp-postprocessing.md b/skills/using-unity/references/urp-postprocessing/urp-postprocessing.md index f7c77f7..0804b62 100644 --- a/skills/using-unity/references/urp-postprocessing/urp-postprocessing.md +++ b/skills/using-unity/references/urp-postprocessing/urp-postprocessing.md @@ -1,6 +1,6 @@ --- name: urp-postprocessing -description: Sets up, configures, and debugs URP post-processing with the Volume framework. Use for bloom, tonemapping, color adjustments, depth of field, vignette, or other Volume overrides. +description: Sets up, configures, and debugs URP post-processing with the Volume framework. Use when asked to add or tune effects such as bloom, tonemapping, depth of field, or to fix Volume overrides that don't display. required_packages: com.unity.render-pipelines.universal: ">=14.0.0" --- @@ -9,7 +9,59 @@ Help the user set up, configure, and debug post-processing effects using URP's V **Goal: The user should have a working visual result with zero console errors after setup.** -## 0. Prerequisite: an Editor you can run C# in +## Important + +- Use the unity cli (`unity command --format json`) and the `unity-cli` and `unity-pipeline` skills for each step. +- Run C# with `unity command script eval --code '<snippet>'`. Don't use `using` directives or unqualified types in the snippet. The compiler reads using `UnityEngine` and a bare AssetDatabase, Volume, or Object causes errors (CS0246 / CS0103 / CS0104). `return` what you want to read; it arrives at `data.result.result`. +- Create a restore point you can roll back to if your changes fail. +- Do only what's asked. Don't change unrelated assets or files. +- Never leave verification code in the user's script. Never build logging or detection they didn't ask for. See [Final step](#final-step). +- Avoid long explanations. + +## Step 1 + +Before you go forward with a workflow or diagnosis: + +1. Open and read the [documentation page(s)](#full-topic-map) that cover the specific subject related to what you intend to do or fix and check if you've missed anything. +2. Name the file(s) you read in your response. + +This is because your training knowledge about Unity might be out of date, incorrect, or for the wrong Unity version. + +## Full topic map + +Where the URP manual lives depends on the Unity version, so check the version first. Read the Unity version from `ProjectSettings/ProjectVersion.txt` (for example `6000.0` from `6000.0.58f1`), and each package's major.minor from `Packages/packages-lock.json` (for example `17.0` from `17.0.4`). + +**Unity 6000.0 or later:** if the Editor install folder has a `Data/Documentation` folder (eg `...Unity/Hub/Editor/6000.6.0b2/Editor/Data/Documentation`), read the html files from the `en/Manual` folder. Otherwise the docs pages are online at `https://docs.unity.com/en-us/engine/<VERSION>/manual/post-processing-and-full-screen-effects/urp/`. + +**Earlier than Unity 6000.0:** the docs pages are local markdown conversions of the URP manual, stored at `<project-folder>/Library/PackageCache/com.unity.render-pipelines.universal@*/`. Read only the .md files in that specific `PackageCache` subfolder. You must not look at non-.md files, or look outside at other Library or PackageCache folders, otherwise it takes too much time. Some page names differ from the list below, so find each page by its title. If that folder has no `.md` files, use the online pages at `https://docs.unity3d.com/Packages/com.unity.render-pipelines.universal@<VERSION>/manual/` instead, because some package versions don't ship their docs. + +Prefer fetching the page directly (for example `WebFetch`) over searching (for example `WebSearch`) — faster and lands on the exact reference. Only fetch what you need, and only search if you don't have the exact URL. Replace `<VERSION>` with the following before fetching: + +- **docs.unity3d.com**: The Unity version, eg `6000.6` +- **Package on docs.unity3d.com**: The package version, eg `@6.6` or `@2.0`. Check the package version if unsure. +- **Engine on docs.unity.com**: The Unity version, eg `6000.3` +- **docs.unity.com**: The product version, eg `7000.0` + +Before fetching, check that `<VERSION>` is listed as a `## Version` heading in https://docs.unity.com/en-us/engine/llms.txt. If it isn't, use the docs.unity3d.com Manual instead. The two sites use different page names, so don't reuse the paths below. Instead, find each page by its title in `https://docs.unity3d.com/<VERSION>/Documentation/Manual/docdata/toc.js`, then fetch `https://docs.unity3d.com/<VERSION>/Documentation/Manual/<link>.html`, where `<link>` is the `link` value next to the title. + +- [Add post-processing in URP](https://docs.unity.com/en-us/engine/<VERSION>/manual/post-processing-and-full-screen-effects/urp/add-post-processing.md) — local `urp/add-post-processing.html`: enabling post-processing on a camera and adding a Volume. +- [Understand volumes in URP](https://docs.unity.com/en-us/engine/<VERSION>/manual/post-processing-and-full-screen-effects/urp/volumes-landing-page/volumes.md) — local `urp/Volumes.html`: Global and Local Volumes and how they blend. +- [Set up a volume in URP](https://docs.unity.com/en-us/engine/<VERSION>/manual/post-processing-and-full-screen-effects/urp/volumes-landing-page/set-up-a-volume.md) — local `urp/set-up-a-volume.html`: creating a Volume and setting its mode. +- [Create a Volume Profile in URP](https://docs.unity.com/en-us/engine/<VERSION>/manual/post-processing-and-full-screen-effects/urp/volumes-landing-page/volume-profile.md) — local `urp/Volume-Profile.html`: creating and assigning Volume Profiles. +- [Configure Volume Overrides in URP](https://docs.unity.com/en-us/engine/<VERSION>/manual/post-processing-and-full-screen-effects/urp/volumes-landing-page/volume-overrides.md) — local `urp/VolumeOverrides.html`: adding overrides and enabling their properties. +- [Volume component reference for URP](https://docs.unity.com/en-us/engine/<VERSION>/manual/post-processing-and-full-screen-effects/urp/volumes-landing-page/volume-component-reference.md) — local `urp/volume-component-reference.html`: Volume component properties. + +### API reference + +The API is `UnityEngine.Rendering.Universal` (effects such as `Bloom`, and `UniversalAdditionalCameraData`), part of the `com.unity.render-pipelines.universal` package, and `UnityEngine.Rendering` (`Volume`, `VolumeProfile`, `VolumeComponent`), part of the `com.unity.render-pipelines.core` package. It is versioned by package version, not Unity version (e.g. `@14.0`, `@17.0`), so check the project's installed package versions before relying on a specific class or method. + +1. Read the installed package versions from `Packages/packages-lock.json`. +2. For each package, fetch and cache `https://docs.unity3d.com/Packages/<package-name>@<version>/xrefmap.yml` (replace `<version>` with the installed package version, e.g. `17.0`). This file maps every public API member's fully qualified name to its docs page `href` (e.g. `href: api/UnityEngine.Rendering.Universal.Bloom.html` => `https://docs.unity3d.com/Packages/com.unity.render-pipelines.universal@17.0/api/UnityEngine.Rendering.Universal.Bloom.html`). +3. Grep the yml file locally for a class or method instead of refetching per lookup. Don't read the whole file. + +Always fetch the version matching the installed package rather than relying on training knowledge, since APIs are frequently marked obsolete between major versions. + +## Step 2. Prerequisite: an Editor you can run C# in Volume profiles, `VolumeParameter.overrideState`, and the camera's post-processing flags are Editor/runtime object state — the checks and edits below all run C# inside a live Editor. @@ -25,7 +77,7 @@ Run C# through the connected Editor with the `script eval` command. Discover its from `unity command --format json` rather than assuming one — the inline form is `unity command script eval --caller plugin --skill urp-postprocessing --code '<snippet>'`, and some Pipeline versions also register `script eval_file` for running a snippet from a file. **Check the catalog before reaching for -`script eval_file`; it is frequently absent.** `unity command` defaults to a 30 second timeout. +`script eval_file`; it is frequently absent.** `script eval`'s default timeout depends on the Pipeline version, so read it from the command's schema (`unity command --detail full --format json`) and pass `--timeout <seconds>` for a slow call. ### Passing C# to `script eval` @@ -40,7 +92,7 @@ compile error rather than a warning: Where a snippet below is written as a file — with usings, for readability, or because it is meant to be saved into the project — qualify the types before passing it to `script eval`. -## 0. Pre-Flight Checks +## Step 3. Pre-Flight Checks Before configuring any effect, **verify all checks**. Fix failures first. @@ -59,7 +111,7 @@ Run this to verify the setup programmatically: // allowed, so every type is fully qualified. var report = new System.Text.StringBuilder(); -// 1. Check URP is active — a hard stop, so throw: it fails the eval loudly +// 1. Check URP is active — a hard stop, so throw: it fails `script eval` loudly var urpAsset = UnityEngine.Rendering.Universal.UniversalRenderPipeline.asset; if (urpAsset == null) throw new System.Exception("URP is not the active render pipeline."); @@ -95,7 +147,7 @@ foreach (var vol in volumes) return report.Length == 0 ? "Post-processing setup looks correct." : report.ToString(); ``` -## 1. Volume Setup +## Step 4. Volume Setup Effects are added as **VolumeComponent overrides** on a **VolumeProfile** (a `ScriptableObject`). @@ -106,7 +158,7 @@ Effects are added as **VolumeComponent overrides** on a **VolumeProfile** (a `Sc - `blendDistance` (float) — outer distance in world units to start blending from (0 = no blend, instant transition at collider boundary). - `weight` (float, 0–1) — scales the volume's overall influence. -## 2. Post-Processing Effects +## Step 5. Post-Processing Effects All effects are `VolumeComponent` subclasses added as overrides on a `VolumeProfile` via `profile.Add<T>()`. Check existence with `profile.Has<T>()` or `profile.TryGet<T>(out var t)`. Remove with `profile.Remove<T>()`. @@ -118,7 +170,7 @@ When configuring a specific effect, load the full API reference: For code templates: - [references/code-templates.md](references/code-templates.md) — Global Volume setup, camera post-processing, and profile modification templates -## 3. Anti-Hallucination Rules +## Step 6. Anti-Hallucination Rules ### Required Usings @@ -147,7 +199,7 @@ using UnityEngine.Rendering.Universal; // Bloom, Tonemapping, ColorAdjustments, - **`sharedProfile`** = returns the asset directly (edits persist to disk). **`profile`** = auto-clones into an instance if needed (safe for runtime edits). Check with `volume.HasInstantiatedProfile()`. - **`profile.Add<T>(bool overrides = false)`** — pass `true` to auto-enable `overrideState` on all parameters of the added component. -## 4. Debugging Checklist +## Step 7. Debugging Checklist When post-processing isn't working, check in order: @@ -160,7 +212,7 @@ When post-processing isn't working, check in order: 7. `UniversalRenderPipeline.asset.supportsHDR` is `true`? Required for Bloom and Tonemapping. 8. Viewing in **Game view**? Scene view has a separate post-processing toggle in its toolbar. -## 5. Common Recipes +## Step 8. Common Recipes Format: Effect property=value. Bloom values are threshold/intensity/scatter. @@ -172,9 +224,19 @@ Format: Effect property=value. Bloom values are threshold/intensity/scatter. **Clean/Mobile:** Tonemapping mode=Neutral, ColorAdjustments postExposure=0.2, Bloom threshold=1.0 intensity=0.3 (subtle). Avoid FilmGrain, MotionBlur, DepthOfField on mobile. -## 6. Final Confirmation +## Final step + +Do the following checks: + +1. Check the project has zero console errors. Use `console status` for counts. +2. Stop there unless the user asked you to prove it works or you suspect a specific fault. +3. If you do enter Play mode, do it once only to chase a fault you already suspect. Read the world through `script eval` rather than adding logging. Take no screenshots as they take too much time. + +If a check fails, go back and reread the [docs pages](#full-topic-map) to find out what you missed. + +## Final report -After setup, report to user: +Give the user a concise but not dense checklist of what you did and why, including any incidental side effects (for example, settings you toggled to test something, or temporary files you created). If the user needs to follow up with more steps or decisions, list them. After setup, report to user: ``` Post-Processing Setup Complete diff --git a/skills/using-unity/references/validate-urp-render-graph-renderer-feature/SECURITY.md b/skills/using-unity/references/validate-urp-render-graph-renderer-feature/SECURITY.md new file mode 100644 index 0000000..48089ec --- /dev/null +++ b/skills/using-unity/references/validate-urp-render-graph-renderer-feature/SECURITY.md @@ -0,0 +1,16 @@ +# Security notes: validate-urp-render-graph-renderer-feature + +This skill has the agent read state from the user's open Unity Editor through `unity command script eval` when it checks a suspected fault in Play mode while reviewing a Render Graph renderer feature. Automated skill scanners flag running code in the Editor as a powerful capability. It is intentional, and it is limited by the safeguards below. + +## Accepted risks + +| Risk | Capability | Why it is accepted | +|---|---|---| +| `SEC_POWER_CAP` | Runs C# in the user's open Editor through `unity command script eval` | It only reaches the Editor the user already has open, on their own machine, as that user, so it grants nothing they couldn't do themselves. `script eval` sits behind the Pipeline capability gate. No code fetched from a remote source is run. | + +## Mitigations + +- **Only the user's own Editor.** `unity command script eval` talks to the Editor open on this machine. It can't reach another machine or another user's Editor. +- **Capability gate.** `script eval` is only available when the project's Pipeline package provides it. +- **No remote code.** The agent runs C# it writes itself to read Editor state. Nothing downloaded from outside is executed. +- **Review only.** The skill doesn't edit the user's files unless they ask for the fixes, enters Play mode at most once to chase a fault it already suspects, and reads state instead of adding logging or verification code. It creates a restore point just before its first edit. diff --git a/skills/using-unity/references/validate-urp-render-graph-renderer-feature/references/api-reference.md b/skills/using-unity/references/validate-urp-render-graph-renderer-feature/references/api-reference.md new file mode 100644 index 0000000..b4ca7b6 --- /dev/null +++ b/skills/using-unity/references/validate-urp-render-graph-renderer-feature/references/api-reference.md @@ -0,0 +1,19 @@ +# API reference + +The API is `UnityEngine.Rendering.Universal` (`ScriptableRendererFeature`, `ScriptableRenderPass`, `UniversalResourceData`), part of the `com.unity.render-pipelines.universal` package, and `UnityEngine.Rendering.RenderGraphModule` (`RenderGraph`, `TextureHandle`, builders, `AddBlitPass`), part of the `com.unity.render-pipelines.core` package. Both are versioned by package version, not Unity version (e.g. `@17.0`, `@17.3`), so check the project's installed URP version before relying on a specific class or method. + +1. Use the `unity-cli` skill, or `Packages/packages-lock.json`, to check the installed URP version. The core package has the same version. +2. Fetch and cache `https://docs.unity3d.com/Packages/<package-name>@<version>/xrefmap.yml` for each package (replace `<version>` with the installed package version, e.g. `17.3`). This file maps every public API member's fully qualified name to its docs page `href` (e.g. `href: api/UnityEngine.Rendering.Universal.ScriptableRendererFeature.html` => `https://docs.unity3d.com/Packages/com.unity.render-pipelines.universal@17.3/api/UnityEngine.Rendering.Universal.ScriptableRendererFeature.html`). +3. Grep the yml files locally for a class or method instead of refetching per lookup. Don't read the whole file. + +Always fetch the version matching the installed package rather than relying on training knowledge, since APIs are frequently marked obsolete between major versions. + +Engine types the code uses, such as `Material` and `RenderTextureDescriptor`, are in `UnityEngine`, versioned by Unity version: + +1. If the Editor install folder has a `Data/Documentation` folder, grep the html files in `<editor-install>/Editor/Data/Documentation/en/ScriptReference/`, and skip the remaining steps. +2. Otherwise, fetch and cache `https://docs.unity3d.com/<VERSION>/Documentation/ScriptReference/xrefmap.yml` (replace `<VERSION>` with the Unity version, e.g. `6000.3`). This file lists every public API member's fully qualified name as a `uid` (e.g. `uid: 'UnityEngine.Material.SetTexture(System.String,UnityEngine.Texture)'`). +3. Grep the yml file locally for a class or method instead of refetching per lookup. The file is large (about 6 MB), so don't read the whole file. +4. Convert the `uid` to a markdown page: remove the parameters in brackets, lowercase it, replace `.` with `/`, and add `.md`. Then fetch `https://docs.unity.com/en-us/engine/<VERSION>/script-reference/<converted uid>`. For example, `UnityEngine.Material.SetTexture(System.String,UnityEngine.Texture)` => `https://docs.unity.com/en-us/engine/6000.3/script-reference/unityengine/material/settexture.md`. All overloads are on the same page. + - Constructors use `ctor`, and indexers use `item`. For operators, fetch the class page and follow its link. + - Links inside the pages start with `/engine/`. Add `https://docs.unity.com/en-us` before them. + - If the page doesn't exist for that Unity version, use the `href` in the `xrefmap.yml` entry instead (e.g. `href: 'RenderTextureDescriptor.html'` => `https://docs.unity3d.com/6000.3/Documentation/ScriptReference/RenderTextureDescriptor.html`). diff --git a/skills/using-unity/references/validate-urp-render-graph-renderer-feature/references/pass-simplification.md b/skills/using-unity/references/validate-urp-render-graph-renderer-feature/references/pass-simplification.md new file mode 100644 index 0000000..71e0a30 --- /dev/null +++ b/skills/using-unity/references/validate-urp-render-graph-renderer-feature/references/pass-simplification.md @@ -0,0 +1,42 @@ +# Pass simplification checks + +Checks 5 and 6 of the validation checklist: when a custom raster pass should be a built-in copy or blit helper. + +## Contents + +- [5. Manual Copy Pass Simplification](#5-manual-copy-pass-simplification) +- [6. Manual Blit Pass Simplification](#6-manual-blit-pass-simplification) + +## 5. Manual Copy Pass Simplification +Check that: +- simple texture copy operations are not implemented as full custom raster passes when a built-in Render Graph helper is sufficient +- passes that only read one texture and write it unchanged to another target are simplified where appropriate +- the implementation prefers the most appropriate built-in helper for the target API/platform context +- `AddCopyPass(...)` is not recommended by default if a more compatible `AddBlitPass(...)` overload should be preferred in the current environment + +Flag as an issue when: +- a raster pass exists only to copy one texture into another +- the pass uses no material and no custom processing +- the render function only performs a simple blit/copy equivalent +- the implementation uses a full custom raster pass where a built-in copy/blit helper would express the same behavior more directly + +Prefer: +- the appropriate `AddBlitPass(...)` overload for straightforward copy-like operations when that is the recommended and more compatible path +- `AddCopyPass(...)` only when it is explicitly appropriate and supported for the target API/platform context +- a custom raster pass only when the copy requires additional logic or non-trivial behavior + +## 6. Manual Blit Pass Simplification +Check that: +- straightforward fullscreen material blits are not implemented as custom raster passes when `renderGraph.AddBlitPass(...)` would express the same behavior more directly +- custom raster passes are only used for blits when additional logic or non-trivial behavior is actually required +- simple source-to-destination material blits use the most direct render graph helper available + +Flag as an issue when: +- a raster pass reads one source texture and writes one destination texture +- the pass uses a material but no additional custom pass logic +- the render function only performs a simple fullscreen blit +- `renderGraph.AddBlitPass(...)` would provide an equivalent result more clearly + +Prefer: +- `renderGraph.AddBlitPass(...)` for straightforward fullscreen material blits +- a custom raster pass only when extra logic, multiple operations, conditional behavior, or special setup is actually required diff --git a/skills/using-unity/references/validate-urp-render-graph-renderer-feature/validate-urp-render-graph-renderer-feature.md b/skills/using-unity/references/validate-urp-render-graph-renderer-feature/validate-urp-render-graph-renderer-feature.md index d3b43d6..8db113b 100644 --- a/skills/using-unity/references/validate-urp-render-graph-renderer-feature/validate-urp-render-graph-renderer-feature.md +++ b/skills/using-unity/references/validate-urp-render-graph-renderer-feature/validate-urp-render-graph-renderer-feature.md @@ -1,12 +1,60 @@ --- name: validate-urp-render-graph-renderer-feature -description: Reviews a Unity 6 URP ScriptableRendererFeature that uses the Render Graph API, checking resource wiring, material binding, execution structure, and best practices. Use to validate a renderer feature. +description: Reviews a Unity 6 URP ScriptableRendererFeature that uses the Render Graph API, checking resource wiring, material binding, execution structure, and best practices. Use when asked to review a URP Render Graph renderer feature. --- # Skill: Validate a Unity URP Render Graph Renderer Feature ## Purpose Review a Unity 6+ URP Render Graph `ScriptableRendererFeature` and its associated pass implementation for correctness issues related to material binding, resource wiring, render graph texture creation, static render function structure, global resource exposure, and API/version usage. +## Important +- Use the unity cli (`unity command --format json`) and the `unity-cli` and `unity-pipeline` skills for each step. +- Run C# with `unity command script eval --caller plugin --skill validate-urp-render-graph-renderer-feature --code '<snippet>'`. Don't use `using` directives or unqualified types in the snippet, because the compiler only reads `using UnityEngine`, and a bare `AssetDatabase` or `Object` causes errors (CS0246 / CS0103 / CS0104). `return` what you want to read; it arrives at `data.result.result`. +- Before making changes, establish a baseline of the current behavior so you can tell whether a later result is actually caused by your change. +- Create a restore point you can roll back to if your changes fail. +- Do only what's asked. Don't change unrelated assets or files. +- Never leave verification code in the user's script. Never build logging or detection they didn't ask for. See [Final step](#final-step). +- Avoid long explanations. +- This is a review. Don't edit the user's files unless they ask you to apply the fixes, and create the restore point just before your first edit. + +## Full topic map +Before you go forward with a workflow or diagnosis: + +1. Open and read the [documentation page(s)](#full-topic-map) that cover the specific subject related to what you intend to do or fix and check if you've missed anything. +2. Name the file(s) you read in your response. + +This is because your training knowledge about Unity might be out of date, incorrect, or for the wrong Unity version. + +If the Editor install folder has a `Data/Documentation` folder (eg `...Unity/Hub/Editor/6000.6.0b2/Editor/Data/Documentation`), read the html files from the `en/Manual` folder. + +Otherwise the docs pages are online as markdown at `https://docs.unity.com/en-us/engine/<VERSION>/manual/render-pipelines/universal-render-pipeline/customizing-urp/`. Prefer `WebFetch` over `WebSearch` — faster and lands on the exact reference. Only fetch what you need. Replace `<VERSION>` with the following before fetching: + +- **docs.unity3d.com**: The Unity version, eg `6000.6` +- **Package on docs.unity3d.com**: The package version, eg `@6.6` or `@2.0`. Check the package version if unsure. +- **docs.unity.com**: The Unity version, eg `6000.0` + +For these Engine manual pages, `<VERSION>` is the Unity version. Get it from `ProjectSettings/ProjectVersion.txt`, using only the major and minor parts. For example, get `6000.0` from `6000.0.58f1`. + +Local file names below are relative to `en/Manual/urp/`. + +- [Write a render pass using the render graph system in URP](https://docs.unity.com/en-us/engine/<VERSION>/manual/render-pipelines/universal-render-pipeline/customizing-urp/render-graph/write-render-pass.md) — local `render-graph-write-render-pass.html`: pass setup, `PassData`, and the render function. +- [Blit using the render graph system in URP](https://docs.unity.com/en-us/engine/<VERSION>/manual/render-pipelines/universal-render-pipeline/customizing-urp/render-graph/blit.md) — local `render-graph-blit.html`: `AddBlitPass` and blit passes. +- [Create a temporary texture for a single frame in URP](https://docs.unity.com/en-us/engine/<VERSION>/manual/render-pipelines/universal-render-pipeline/customizing-urp/render-graph/working-with-textures/create-a-texture.md) — local `render-graph-create-a-texture.html`: creating a texture from a graph-derived descriptor. +- [Create a texture as a global texture in URP](https://docs.unity.com/en-us/engine/<VERSION>/manual/render-pipelines/universal-render-pipeline/customizing-urp/render-graph/working-with-textures/pass-textures-between-passes/create-global-texture.md) — local `render-graph-create-global-texture.html`: making a texture global with `SetGlobalTextureAfterPass`. +- [Inject a render pass with a Scriptable Renderer Feature in URP](https://docs.unity.com/en-us/engine/<VERSION>/manual/render-pipelines/universal-render-pipeline/customizing-urp/inject-a-render-pass/inject-a-pass-using-a-scriptable-renderer-feature.md) — local `renderer-features/scriptable-renderer-features/inject-a-pass-using-a-scriptable-renderer-feature.html`: adding a pass from a `ScriptableRendererFeature`. + +### API reference + +Before relying on a specific URP, Render Graph, or Engine class or method, follow the lookup steps in [API reference](references/api-reference.md) for the project's installed versions. + +## Procedure +1. Get the Unity version from `ProjectSettings/ProjectVersion.txt` and the URP version from `Packages/packages-lock.json` (or `Packages/manifest.json` if there's no lock file), or from the user. For each value you can't find, assume Unity 6000.0 or URP 17.0, name the assumption in your report, and carry on. +2. Read the code the user gave you: the `ScriptableRendererFeature`, its pass, and any shader the pass binds. If there's no code, ask for it. +3. Read the documentation pages that cover the APIs the code uses. +4. Run sections 1–8 of the [Validation Checklist](#validation-checklist) against the code. +5. Report back in the [Output Format](#output-format). +6. If the user asks you to apply the fixes, apply them, run the [Final step](#final-step), then tell the user what you changed and whether the checks passed. + ## When to Use Use this skill when: - reviewing AI-generated Unity URP Render Graph renderer feature code @@ -16,7 +64,7 @@ Use this skill when: - reviewing whether a custom raster/blit/copy pass uses the most appropriate Render Graph helper APIs ## Inputs -The skill should expect: +Expect: - **Unity version** - **URP version** - **Render Graph renderer feature code to review** @@ -32,7 +80,7 @@ The skill should expect: - required material/shader properties ## Output Format -The skill must return results in the following structure: +Return results in the following structure: ### 1. Validation Summary A short overall assessment of the implementation. @@ -62,9 +110,9 @@ Check that: - null handling exists where required - declared materials are actually used - **all required material inputs are bound before execution** -- **the primary input texture is explicitly bound when the shader expects one** +- **the primary input texture is explicitly bound when the shader expects one**, because otherwise the shader samples a default or stale texture without any error - auxiliary textures and parameter textures are also bound explicitly -- texture/property binding matches the shader’s expected property names +- texture/property binding matches the shader’s expected property names, because a misspelled name sets a property the shader never reads Flag as an issue when: - a material is declared or passed but not actually used @@ -85,9 +133,9 @@ Prefer patterns where: Check that: - sampled/read textures, write targets, and auxiliary textures are clearly distinguished - textures used with `UseTexture(...)` are appropriate for read access -- textures used with `SetRenderAttachment(...)` are appropriate as write targets +- textures used with `SetRenderAttachment(...)` are appropriate as write targets, because Render Graph uses these read/write declarations to order passes and allocate resources - source, destination, and auxiliary resources are not confused -- all expected textures are explicitly wired +- all expected textures are explicitly wired, because Render Graph throws an error when a render function accesses a texture the pass didn't declare, and it can't track dependencies or lifetimes for it. - texture property names are explicit and consistent when materials are involved - the implementation does not invent texture availability - multi-texture resource usage is handled explicitly rather than implicitly @@ -101,13 +149,13 @@ Flag as an issue when: ### 3. Execution Structure / Static Render Function Check that: -- the render function is declared as `static` +- the render function is declared as `static`, because a static function can't capture instance state, so it reads only the `PassData` recorded for this pass - the execution structure matches the target pass type and API style - pass data is wired correctly into execution - resources are accessed in the correct stage - execution logic is consistent with the intended render pass behavior - every `PassData` field used by the render function is explicitly assigned during pass setup for the current recording -- the implementation does not rely on default values or previously assigned `PassData` state +- the implementation does not rely on default values or previously assigned `PassData` state, because Render Graph pools `PassData` objects and reuses them across passes and frames - resource handles stored in `PassData` are assigned fresh for the current frame/pass recording and are not left dangling from prior usage Flag as an issue when: @@ -157,43 +205,15 @@ Examples: RenderTextureDescriptor desc = resourceData.activeColorTexture.GetDescriptor(renderGraph); desc.depthBufferBits = 0; desc.name = "New name"; -// other desired paramters +// other desired parameters passData.targetTexture = renderGraph.CreateTexture(desc); ``` ### 5. Manual Copy Pass Simplification -Check that: -- simple texture copy operations are not implemented as full custom raster passes when a built-in Render Graph helper is sufficient -- passes that only read one texture and write it unchanged to another target are simplified where appropriate -- the implementation prefers the most appropriate built-in helper for the target API/platform context -- `AddCopyPass(...)` is not recommended by default if a more compatible `AddBlitPass(...)` overload should be preferred in the current environment - -Flag as an issue when: -- a raster pass exists only to copy one texture into another -- the pass uses no material and no custom processing -- the render function only performs a simple blit/copy equivalent -- the implementation uses a full custom raster pass where a built-in copy/blit helper would express the same behavior more directly - -Prefer: -- the appropriate `AddBlitPass(...)` overload for straightforward copy-like operations when that is the recommended and more compatible path -- `AddCopyPass(...)` only when it is explicitly appropriate and supported for the target API/platform context -- a custom raster pass only when the copy requires additional logic or non-trivial behavior +Flag a custom raster pass that only copies one texture to another with no material or custom logic. Read the checks in [references/pass-simplification.md](references/pass-simplification.md#5-manual-copy-pass-simplification), because the right helper (`AddBlitPass` or `AddCopyPass`) depends on the target API and platform. ### 6. Manual Blit Pass Simplification -Check that: -- straightforward fullscreen material blits are not implemented as custom raster passes when `renderGraph.AddBlitPass(...)` would express the same behavior more directly -- custom raster passes are only used for blits when additional logic or non-trivial behavior is actually required -- simple source-to-destination material blits use the most direct render graph helper available - -Flag as an issue when: -- a raster pass reads one source texture and writes one destination texture -- the pass uses a material but no additional custom pass logic -- the render function only performs a simple fullscreen blit -- `renderGraph.AddBlitPass(...)` would provide an equivalent result more clearly - -Prefer: -- `renderGraph.AddBlitPass(...)` for straightforward fullscreen material blits -- a custom raster pass only when extra logic, multiple operations, conditional behavior, or special setup is actually required +Flag a custom raster pass that only does a fullscreen material blit from one source to one destination. Read the checks in [references/pass-simplification.md](references/pass-simplification.md#6-manual-blit-pass-simplification), because `renderGraph.AddBlitPass(...)` usually expresses it more directly. ### 7. Global Resource Exposure Check that: @@ -235,13 +255,13 @@ Classification guidance: - treat unnecessary input declarations as higher severity when they are likely to introduce additional copies or other measurable runtime cost ## Guardrails -The skill must: -- avoid inventing unsupported APIs -- distinguish **confirmed** issues from **likely** issues -- prefer minimal targeted fixes over broad rewrites -- explain why each issue matters -- flag hidden coupling and unnecessary global state -- state when the provided code is insufficient for full certainty +Always: +- avoid inventing unsupported APIs, because a fix that calls an API that doesn't exist won't compile +- distinguish **confirmed** issues from **likely** issues, because likely issues depend on code or context you haven't seen +- prefer minimal targeted fixes over broad rewrites, because rewrites are harder to review and can break behavior the user relies on +- explain why each issue matters, so the user can judge whether to fix it +- flag hidden coupling and unnecessary global state, because they keep resources alive longer and make passes harder to change +- state when the provided code is insufficient for full certainty, so the user knows what to send next ## Non-Goals - guarantee runtime correctness @@ -249,21 +269,14 @@ The skill must: - validate unrelated gameplay logic - validate shader internals unless directly relevant to pass wiring or binding -## Evaluation Criteria -A successful validation should: -- catch real wiring and API issues -- identify suspicious but plausible mistakes -- provide actionable fixes -- avoid false certainty -- improve trust in generated render pass code - -## Notes for Future Expansion -As new recurring issues are discovered, extend this checklist with additional rules such as: -- pass ordering / injection point validation -- resource lifetime and cleanup checks -- read/write hazard detection -- unnecessary copies or allocations -- camera depth/color dependency validation -- multi-pass dependency validation -- override material correctness -- pass configuration +## Final step +Do the following checks: + +1. Check the project has zero console errors. Use `console status` for counts. +2. Stop there unless the user asked you to prove it works or you suspect a specific fault. +3. If you do enter Play mode, do it once only to chase a fault you already suspect. Read the world through `script eval` rather than adding logging. Take no screenshots as they take too much time. + +If a check fails, go back and reread the [docs pages](#full-topic-map) to find out what you missed. + +## Final report +Give the user a concise checklist of what you did and why. If you applied fixes, list the files you changed and any side effects, such as the restore point you created. List any follow-up steps or decisions the user needs, such as the [Missing Information](#6-missing-information) you still need.