From 13f57e06641313b26b8d062922b61feb8bad081e Mon Sep 17 00:00:00 2001 From: "pre-shared-workflows-auth[bot]" <168739156+pre-shared-workflows-auth[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 08:18:05 +0000 Subject: [PATCH] chore: publish 27 skills (2d-pixel-perfect, asset-transformer-toolkit, audio-setup-mixers, +24) --- skills/using-unity/SKILL.md | 16 +- .../2d-pixel-perfect/2d-pixel-perfect.md | 208 ------- .../asset-transformer-toolkit/SECURITY.md | 15 - .../asset-transformer-toolkit.md | 39 -- .../references/lods.md | 61 --- .../audio-setup-mixers/audio-setup-mixers.md | 127 ----- .../references/build-gtk/build-gtk.md | 4 + .../configure-2d-pixel-perfect/SECURITY.md | 17 + .../configure-2d-pixel-perfect.md | 302 +++++++++++ .../references/api-reference.md | 0 .../references/camera-setup-builtin.cs | 0 .../references/camera-setup-urp.cs | 0 .../references/pipeline-detection.cs | 0 .../references/sprite-settings.cs | 0 .../craft-game-floors/craft-game-floors.md | 4 +- .../references/camera-rigs.md | 2 +- .../references/game-audio.md | 4 +- .../create-2d-physics/create-2d-physics.md | 2 +- .../SECURITY.md | 15 + .../create-tile-palette-or-rule-tiles.md | 6 +- .../fix-3d-physics-collisions.md | 8 +- .../generate-editor-search-query.md | 91 +++- .../implement-in-app-purchases/SECURITY.md | 15 + .../implement-in-app-purchases.md | 6 +- .../SECURITY.md | 15 + .../import-and-optimize-cad-models.md | 101 ++++ .../references/create-importer.md | 34 +- .../references/lods.md | 70 +++ .../references/rule-api.md | 2 + .../references/ruleblock-api.md | 2 + .../references/ruleset-api.md | 2 + .../references/rulesets-and-actions.md | 63 ++- .../initialize-ai-navigation/SECURITY.md | 15 + .../initialize-ai-navigation.md | 8 +- .../localize-unity-project/SECURITY.md | 15 + .../localize-unity-project.md | 4 +- .../references/translation-strategy.md | 2 +- .../manage-sprite-atlas/SECURITY.md | 16 + .../manage-sprite-atlas.md | 365 +++++-------- .../references/addressables-delivery.md | 7 +- .../manage-sprite-atlas/references/api.md | 416 ++------------ .../references/best-practices.md | 43 +- .../references/categorization-patterns.md | 14 + .../references/common-errors.md | 138 +---- .../references/custom-packing.md | 21 +- .../references/docs-map.md | 28 + .../references/manual-authoring.md | 11 +- .../references/workflow.md | 28 + .../authoringvsruntime.cs | 0 .../buildaddressablespostprocess.cs | 0 .../cacheloadedatlases.cs | 0 .../cleanupbatchoperations.cs | 0 .../createandconfiguremasteratlas.cs | 0 .../custompackersetup.cs | 0 .../deprecatedmethods.cs | 0 .../dontmodifywithoutsaving.cs | 0 .../dontpackinruntimebuilds.cs | 0 .../dontscriptspriteatlasineditor.cs | 0 .../editorconfiguration.cs | 0 .../enablespritepacking.cs | 0 .../gridspritepacker.cs | 0 .../handlelatebinding.cs | 0 .../{resources => scripts}/handlenullcases.cs | 0 .../{resources => scripts}/migratev1tov2.cs | 0 .../{resources => scripts}/multipagepacker.cs | 0 .../optimizetexturesettings.cs | 0 .../{resources => scripts}/packerdebugging.cs | 0 .../{resources => scripts}/packtransform.cs | 0 .../{resources => scripts}/platformnames.cs | 0 .../queryspritesefficiently.cs | 0 .../registercallbacks.cs | 0 .../runtimeatlasloader.cs | 0 .../runtimespriteaccess.cs | 0 .../savespriteatlasasset.cs | 0 .../scriptablepacker.cs | 0 .../setincludeinbuild.cs | 0 .../sizeoptimizedpacker.cs | 0 .../spriteatlaslatebinding.cs | 0 .../spriteatlasprebuildgenerator.cs | 0 .../{resources => scripts}/spritedata.cs | 0 .../{resources => scripts}/spritepack.cs | 0 .../{resources => scripts}/texturedata.cs | 0 .../updatebuildscripts.cs | 0 .../updatesettingsconfiguration.cs | 0 .../usevariantswisely.cs | 0 .../{resources => scripts}/variantatlas.cs | 0 .../migrate-birp-to-urp.md | 508 +++--------------- .../references/assess-migration-state.md | 31 ++ .../references/complex-shader-situations.md | 12 +- .../references/custom-shader-triage.md | 10 +- .../references/docs-map.md | 18 + .../references/eval-execution.md | 60 +++ .../references/gather-requirements.md | 29 + .../references/implementation-patterns.md | 2 +- .../references/migration-gates.md | 50 ++ .../references/migration-workflow.md | 16 +- .../parity-validation-troubleshooting.md | 128 +++++ .../references/quality-settings-map.md | 10 +- .../references/setup-and-conversion.md | 141 +++++ .../optimize-audio/optimize-audio.md | 222 ++++---- .../audio-import-api.md | 25 +- .../references/platform-settings.md | 32 ++ .../references/troubleshooting.md | 35 ++ .../resources/platform-settings.md | 48 -- .../optimize-text-mesh-pro/SECURITY.md | 15 + .../optimize-text-mesh-pro.md | 6 +- .../references/optimize-web/optimize-web.md | 380 +------------ .../references/editor-scripting.md | 110 ++++ .../references/optimization-areas.md | 203 +++++++ .../references/troubleshooting.md | 55 ++ .../SECURITY.md | 2 +- .../references/api.md | 12 +- .../route-audio-to-mixer-groups.md | 213 ++++++++ .../setup-vivox-voice-chat/SECURITY.md | 5 +- .../setup-vivox-voice-chat.md | 2 +- .../SECURITY.md | 16 + .../{resources => references}/all_hints.hlsl | 0 .../shader-graph-create-custom-node.md | 99 +++- .../sprite-editor/references/api_reference.md | 2 + .../sprite-editor/references/background.md | 2 + .../references/sprite-editor/sprite-editor.md | 113 +++- .../sprite-segment-3x3grid/SECURITY.md | 15 + .../sprite-segment-3x3grid.md | 4 +- .../references/unity-pipeline/SECURITY.md | 6 +- .../unity-pipeline/unity-pipeline.md | 261 +++++---- .../references/urp-postprocessing/SECURITY.md | 2 +- .../references/code-templates.md | 9 +- .../urp-postprocessing/urp-postprocessing.md | 86 ++- .../SECURITY.md | 16 + .../references/api-reference.md | 19 + .../references/pass-simplification.md | 42 ++ ...idate-urp-render-graph-renderer-feature.md | 143 ++--- 132 files changed, 3098 insertions(+), 2479 deletions(-) delete mode 100644 skills/using-unity/references/2d-pixel-perfect/2d-pixel-perfect.md delete mode 100644 skills/using-unity/references/asset-transformer-toolkit/SECURITY.md delete mode 100644 skills/using-unity/references/asset-transformer-toolkit/asset-transformer-toolkit.md delete mode 100644 skills/using-unity/references/asset-transformer-toolkit/references/lods.md delete mode 100644 skills/using-unity/references/audio-setup-mixers/audio-setup-mixers.md create mode 100644 skills/using-unity/references/configure-2d-pixel-perfect/SECURITY.md create mode 100644 skills/using-unity/references/configure-2d-pixel-perfect/configure-2d-pixel-perfect.md rename skills/using-unity/references/{2d-pixel-perfect => configure-2d-pixel-perfect}/references/api-reference.md (100%) rename skills/using-unity/references/{2d-pixel-perfect => configure-2d-pixel-perfect}/references/camera-setup-builtin.cs (100%) rename skills/using-unity/references/{2d-pixel-perfect => configure-2d-pixel-perfect}/references/camera-setup-urp.cs (100%) rename skills/using-unity/references/{2d-pixel-perfect => configure-2d-pixel-perfect}/references/pipeline-detection.cs (100%) rename skills/using-unity/references/{2d-pixel-perfect => configure-2d-pixel-perfect}/references/sprite-settings.cs (100%) create mode 100644 skills/using-unity/references/create-tile-palette-or-rule-tiles/SECURITY.md create mode 100644 skills/using-unity/references/implement-in-app-purchases/SECURITY.md create mode 100644 skills/using-unity/references/import-and-optimize-cad-models/SECURITY.md create mode 100644 skills/using-unity/references/import-and-optimize-cad-models/import-and-optimize-cad-models.md rename skills/using-unity/references/{asset-transformer-toolkit => import-and-optimize-cad-models}/references/create-importer.md (69%) create mode 100644 skills/using-unity/references/import-and-optimize-cad-models/references/lods.md rename skills/using-unity/references/{asset-transformer-toolkit => import-and-optimize-cad-models}/references/rule-api.md (96%) rename skills/using-unity/references/{asset-transformer-toolkit => import-and-optimize-cad-models}/references/ruleblock-api.md (85%) rename skills/using-unity/references/{asset-transformer-toolkit => import-and-optimize-cad-models}/references/ruleset-api.md (96%) rename skills/using-unity/references/{asset-transformer-toolkit => import-and-optimize-cad-models}/references/rulesets-and-actions.md (61%) create mode 100644 skills/using-unity/references/initialize-ai-navigation/SECURITY.md create mode 100644 skills/using-unity/references/localize-unity-project/SECURITY.md create mode 100644 skills/using-unity/references/manage-sprite-atlas/SECURITY.md create mode 100644 skills/using-unity/references/manage-sprite-atlas/references/categorization-patterns.md create mode 100644 skills/using-unity/references/manage-sprite-atlas/references/docs-map.md create mode 100644 skills/using-unity/references/manage-sprite-atlas/references/workflow.md rename skills/using-unity/references/manage-sprite-atlas/{resources => scripts}/authoringvsruntime.cs (100%) rename skills/using-unity/references/manage-sprite-atlas/{resources => scripts}/buildaddressablespostprocess.cs (100%) rename skills/using-unity/references/manage-sprite-atlas/{resources => scripts}/cacheloadedatlases.cs (100%) rename skills/using-unity/references/manage-sprite-atlas/{resources => scripts}/cleanupbatchoperations.cs (100%) rename skills/using-unity/references/manage-sprite-atlas/{resources => scripts}/createandconfiguremasteratlas.cs (100%) rename skills/using-unity/references/manage-sprite-atlas/{resources => scripts}/custompackersetup.cs (100%) rename skills/using-unity/references/manage-sprite-atlas/{resources => scripts}/deprecatedmethods.cs (100%) rename skills/using-unity/references/manage-sprite-atlas/{resources => scripts}/dontmodifywithoutsaving.cs (100%) rename skills/using-unity/references/manage-sprite-atlas/{resources => scripts}/dontpackinruntimebuilds.cs (100%) rename skills/using-unity/references/manage-sprite-atlas/{resources => scripts}/dontscriptspriteatlasineditor.cs (100%) rename skills/using-unity/references/manage-sprite-atlas/{resources => scripts}/editorconfiguration.cs (100%) rename skills/using-unity/references/manage-sprite-atlas/{resources => scripts}/enablespritepacking.cs (100%) rename skills/using-unity/references/manage-sprite-atlas/{resources => scripts}/gridspritepacker.cs (100%) rename skills/using-unity/references/manage-sprite-atlas/{resources => scripts}/handlelatebinding.cs (100%) rename skills/using-unity/references/manage-sprite-atlas/{resources => scripts}/handlenullcases.cs (100%) rename skills/using-unity/references/manage-sprite-atlas/{resources => scripts}/migratev1tov2.cs (100%) rename skills/using-unity/references/manage-sprite-atlas/{resources => scripts}/multipagepacker.cs (100%) rename skills/using-unity/references/manage-sprite-atlas/{resources => scripts}/optimizetexturesettings.cs (100%) rename skills/using-unity/references/manage-sprite-atlas/{resources => scripts}/packerdebugging.cs (100%) rename skills/using-unity/references/manage-sprite-atlas/{resources => scripts}/packtransform.cs (100%) rename skills/using-unity/references/manage-sprite-atlas/{resources => scripts}/platformnames.cs (100%) rename skills/using-unity/references/manage-sprite-atlas/{resources => scripts}/queryspritesefficiently.cs (100%) rename skills/using-unity/references/manage-sprite-atlas/{resources => scripts}/registercallbacks.cs (100%) rename skills/using-unity/references/manage-sprite-atlas/{resources => scripts}/runtimeatlasloader.cs (100%) rename skills/using-unity/references/manage-sprite-atlas/{resources => scripts}/runtimespriteaccess.cs (100%) rename skills/using-unity/references/manage-sprite-atlas/{resources => scripts}/savespriteatlasasset.cs (100%) rename skills/using-unity/references/manage-sprite-atlas/{resources => scripts}/scriptablepacker.cs (100%) rename skills/using-unity/references/manage-sprite-atlas/{resources => scripts}/setincludeinbuild.cs (100%) rename skills/using-unity/references/manage-sprite-atlas/{resources => scripts}/sizeoptimizedpacker.cs (100%) rename skills/using-unity/references/manage-sprite-atlas/{resources => scripts}/spriteatlaslatebinding.cs (100%) rename skills/using-unity/references/manage-sprite-atlas/{resources => scripts}/spriteatlasprebuildgenerator.cs (100%) rename skills/using-unity/references/manage-sprite-atlas/{resources => scripts}/spritedata.cs (100%) rename skills/using-unity/references/manage-sprite-atlas/{resources => scripts}/spritepack.cs (100%) rename skills/using-unity/references/manage-sprite-atlas/{resources => scripts}/texturedata.cs (100%) rename skills/using-unity/references/manage-sprite-atlas/{resources => scripts}/updatebuildscripts.cs (100%) rename skills/using-unity/references/manage-sprite-atlas/{resources => scripts}/updatesettingsconfiguration.cs (100%) rename skills/using-unity/references/manage-sprite-atlas/{resources => scripts}/usevariantswisely.cs (100%) rename skills/using-unity/references/manage-sprite-atlas/{resources => scripts}/variantatlas.cs (100%) create mode 100644 skills/using-unity/references/migrate-birp-to-urp/references/assess-migration-state.md create mode 100644 skills/using-unity/references/migrate-birp-to-urp/references/docs-map.md create mode 100644 skills/using-unity/references/migrate-birp-to-urp/references/eval-execution.md create mode 100644 skills/using-unity/references/migrate-birp-to-urp/references/gather-requirements.md create mode 100644 skills/using-unity/references/migrate-birp-to-urp/references/migration-gates.md create mode 100644 skills/using-unity/references/migrate-birp-to-urp/references/parity-validation-troubleshooting.md create mode 100644 skills/using-unity/references/migrate-birp-to-urp/references/setup-and-conversion.md rename skills/using-unity/references/optimize-audio/{resources => references}/audio-import-api.md (86%) create mode 100644 skills/using-unity/references/optimize-audio/references/platform-settings.md create mode 100644 skills/using-unity/references/optimize-audio/references/troubleshooting.md delete mode 100644 skills/using-unity/references/optimize-audio/resources/platform-settings.md create mode 100644 skills/using-unity/references/optimize-text-mesh-pro/SECURITY.md create mode 100644 skills/using-unity/references/optimize-web/references/editor-scripting.md create mode 100644 skills/using-unity/references/optimize-web/references/optimization-areas.md create mode 100644 skills/using-unity/references/optimize-web/references/troubleshooting.md rename skills/using-unity/references/{audio-setup-mixers => route-audio-to-mixer-groups}/SECURITY.md (96%) rename skills/using-unity/references/{audio-setup-mixers => route-audio-to-mixer-groups}/references/api.md (95%) create mode 100644 skills/using-unity/references/route-audio-to-mixer-groups/route-audio-to-mixer-groups.md create mode 100644 skills/using-unity/references/shader-graph-create-custom-node/SECURITY.md rename skills/using-unity/references/shader-graph-create-custom-node/{resources => references}/all_hints.hlsl (100%) create mode 100644 skills/using-unity/references/sprite-segment-3x3grid/SECURITY.md create mode 100644 skills/using-unity/references/validate-urp-render-graph-renderer-feature/SECURITY.md create mode 100644 skills/using-unity/references/validate-urp-render-graph-renderer-feature/references/api-reference.md create mode 100644 skills/using-unity/references/validate-urp-render-graph-renderer-feature/references/pass-simplification.md diff --git a/skills/using-unity/SKILL.md b/skills/using-unity/SKILL.md index 05e43c0..bb95dd9 100644 --- a/skills/using-unity/SKILL.md +++ b/skills/using-unity/SKILL.md @@ -23,12 +23,10 @@ A skill may tell you to use, load or check for another skill by name, for exampl ## Index (35 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` @@ -36,6 +34,7 @@ A skill may tell you to use, load or check for another skill by name, for exampl - **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,9 +44,10 @@ 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` @@ -55,6 +55,6 @@ A skill may tell you to use, load or check for another skill by name, for exampl - **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..bd3e4d4 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 +`urp-postprocessing` · routing sources into existing mixer groups → `route-audio-to-mixer-groups` · audio import/memory → `optimize-audio` · UI framework choice and construction → `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/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/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 ''`. 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 `` 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/Data/Documentation/en/Manual/.html`). + +Otherwise the docs pages are online at `https://docs.unity.com/en-us/engine//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/Data/Documentation/en/ScriptReference` (eg `Search.SearchService.ShowWindow.html`), and skip the remaining steps. +3. Otherwise, fetch and cache `https://docs.unity3d.com//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//script-reference/`, eg `https://docs.unity.com/en-us/engine//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//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: ` 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 `/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@/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 `` 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@/xrefmap.yml` (replace `` 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 ''`. 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/Data/Documentation/en/Manual/`), and Script Reference pages from `en/ScriptReference`. + +Otherwise the docs pages are online at `https://docs.unity.com/en-us/engine//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 `` 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 `/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@/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//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`). + +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@/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(...)` 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(...)` 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(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()` -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("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> atlasRequested - -// Called when an atlas is registered -static event Action 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/Data/Documentation/en/ScriptReference/` and the online page. Replace `` with the project's Unity version, as described in the Full topic map of the skill. - void OnAtlasRequested(string tag, System.Action callback) - { - // Load atlas from Resources or AssetBundle - SpriteAtlas atlas = Resources.Load($"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//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//script-reference/unityeditor/u2d/spriteatlasimporter.md` +- **SpriteAtlasUtility** (editor preview packing) — local `U2D.SpriteAtlasUtility.html`, online `https://docs.unity.com/en-us/engine//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//script-reference/unityeditor/u2d/spriteatlasextensions.md` +- **SpriteAtlas** (runtime sprite queries) — local `U2D.SpriteAtlas.html`, online `https://docs.unity.com/en-us/engine//script-reference/unityengine/u2d/spriteatlas.md` +- **SpriteAtlasManager** (runtime late-binding events) — local `U2D.SpriteAtlasManager.html`, online `https://docs.unity.com/en-us/engine//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//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()` +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(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(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(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(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/Data/Documentation/en/Manual/`, or `en/ScriptReference/` for Script Reference pages) and its online `.md` page. Replace `` 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//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//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//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//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//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//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//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//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//script-reference/unityeditor/build/ipreprocessbuildwithreport.md` and `https://docs.unity.com/en-us/engine//script-reference/unityeditor/build/ipostprocessbuildwithreport.md`: the build callbacks the generated scripts implement. + +## Addressables package + +Read these from `/Library/PackageCache/com.unity.addressables@*/`, or online under `https://docs.unity3d.com/Packages/com.unity.addressables@/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/Data/Documentation/en/Manual` folder. + +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: + +- **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/Data/Documentation/en/ScriptReference`, and skip to step 6. +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`). +6. For URP APIs, fetch and cache `https://docs.unity3d.com/Packages/com.unity.render-pipelines.universal@/xrefmap.yml` (replace `` 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 ''`. `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()`, 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(); -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 ''`. 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()` 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/Data/Documentation/en/Manual/` (or `en/ScriptReference/` for API pages) when it exists, otherwise the online `.md` page. Replace `` with the project's Unity version, e.g. `6000.3`. + +- [Render pipeline feature comparison](https://docs.unity.com/en-us/engine//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//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//script-reference/unityengine/camera/onrenderimage.md) — local `Camera.OnRenderImage.html` +- [Custom post-processing in URP](https://docs.unity.com/en-us/engine//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//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/Data/Documentation/en/Manual/` (or `en/ScriptReference/` for API pages) when it exists, otherwise the online `.md` page. Replace `` with the project's Unity version, e.g. `6000.3`. + +- [Upgrade custom shaders for URP compatibility](https://docs.unity.com/en-us/engine//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//manual/materials-and-shaders/materials/upgrade-material.md) — local `upgrade-material.html` +- [Render pipeline feature comparison](https://docs.unity.com/en-us/engine//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/Data/Documentation/en/Manual/` (or `en/ScriptReference/` for API pages) when it exists, otherwise the online `.md` page. Replace `` with the project's Unity version, e.g. `6000.3`. + +If a page isn't found, fetch https://docs.unity.com/en-us/engine//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//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//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//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//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//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//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//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//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//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//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()`, 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(); +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(); 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/Data/Documentation/en/Manual/` (or `en/ScriptReference/` for API pages) when it exists, otherwise the online `.md` page. Replace `` 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//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//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//manual/materials-and-shaders/materials/upgrade-material.md) — local `upgrade-material.html` +- [URP asset](https://docs.unity.com/en-us/engine//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//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//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//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/Data/Documentation/en/Manual/` (or `en/ScriptReference/` for API pages) when it exists, otherwise the online `.md` page. Replace `` with the project's Unity version, e.g. `6000.3`. + +- [Convert Built-in quality settings to URP](https://docs.unity.com/en-us/engine//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//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//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//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()` 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 `` 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/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//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//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//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//manual/audio/mixer.md): mixer groups, effects and snapshots. +- **Audio Mixer inspectors** — `AudioMixerInspectors.html`, [online](https://docs.unity.com/en-us/engine//manual/audio/mixer/inspectors.md): effect CPU display, Auto Mixer Suspend. +- **Audio Source** — `class-AudioSource.html`, [online](https://docs.unity.com/en-us/engine//manual/audio/reference/class-audio-source.md): Spatial Blend, rolloff, Output. +- **Audio Listener** — `class-AudioListener.html`, [online](https://docs.unity.com/en-us/engine//manual/audio/reference/class-audio-listener.md): listener behaviour. +- **Audio Profiler module** — `ProfilerAudio.html`, [online](https://docs.unity.com/en-us/engine//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/Data/Documentation/en/ScriptReference` exists, grep its html files and skip the remaining steps. +3. Otherwise, fetch and cache `https://docs.unity3d.com//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//script-reference/`. For example, `UnityEngine.AudioClip.LoadAudioData` => `https://docs.unity.com/en-us/engine//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//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//script-reference/unityeditor/audioimporter.md): `forceToMono`, `loadInBackground`. +- [AudioImporterSampleSettings](https://docs.unity.com/en-us/engine//script-reference/unityeditor/audioimportersamplesettings.md): per-platform sample settings. +- [AssetImporter.SaveAndReimport](https://docs.unity.com/en-us/engine//script-reference/unityeditor/assetimporter/saveandreimport.md): applying importer changes. +- [AudioSettings.GetDSPBufferSize](https://docs.unity.com/en-us/engine//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 ''`. 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 ` 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()`. -- **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 ''`. 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("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( 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//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//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//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//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 ''`. 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 ''`. `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(); -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 ''`. 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 ` 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(); +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 ''`: fully qualified, no +All snippets below are written for `unity command script eval --caller plugin --skill route-audio-to-mixer-groups --code ''`: 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 : "")}, " - + $"group={(group != null ? group.name : "")}"); + + $"group={(group != null ? group.name : "")}"); } 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/Data/Documentation/en/Manual` and `/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//`, 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 `` 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//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//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/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.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//script-reference/`. 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 ''`, 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 ` 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 ''`. 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 `/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@/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 `` 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@/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@/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@/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@/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@/xrefmap.yml` (replace `` 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@/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 `/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@/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/Data/Documentation/en/Manual` folder. Otherwise the docs pages are online at `https://docs.unity.com/en-us/engine//manual/`. +- **Earlier versions**: Read the same local folder if it exists. Otherwise fetch `https://docs.unity3d.com//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 `` 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 `` 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//Documentation/Manual/docdata/toc.js`, then fetch `https://docs.unity3d.com//Documentation/Manual/.html`, where `` is the `link` value next to the title. + +For Engine pages, `` 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, `` 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//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//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//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//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//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@/xrefmap.yml` (replace `` 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@/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//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//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//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//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 ''`, 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 ` 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 ''`. 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/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 ` one group's commands, and `--query ` 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 `, 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 /Library/VP/`. + +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 -` (default 60; the CLI's `--timeout` is the command's own), `--assembly-dir ` (persist -DLLs instead of in-memory); `script.methodreload cleanup --assembly-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 `. -- 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 --type Rigidbody +unity command component set_properties --target --type Rigidbody --properties '{"m_Mass":2}' +unity command prefab create --source --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 -`/Library/VP/` 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 --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 ` 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 /Library/VP/ editor status -# Each clone is its own Editor: keep it ticking before running tests on it -unity command --project-path /Library/VP/ editor set_auto_tick --enabled true -unity command --project-path /Library/VP/ 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 --role server # the GameObject -unity command multiplayer.role set_component --target --type AudioSource --role client # one of its components -unity command multiplayer.role set_component --target --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 `/Library/VP/` 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 /Library/VP/ test run --mode playmode --async-tests true + unity command --project-path /Library/VP/ 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 ` -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 ` 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 `/Library/PackageCache/com.unity.pipeline@*/Documentation~/`; the same pages are -published at `https://docs.unity3d.com/Packages/com.unity.pipeline@/`. Only read what you need. +The Pipeline package ships its documentation in its `Documentation~` folder: for a registry install +`/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@/`. 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; `` 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@/connectivity.md`, where +`` 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 ''`. 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//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 `/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@/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 `` 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 `` 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//Documentation/Manual/docdata/toc.js`, then fetch `https://docs.unity3d.com//Documentation/Manual/.html`, where `` is the `link` value next to the title. + +- [Add post-processing in URP](https://docs.unity.com/en-us/engine//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//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//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//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//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//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/@/xrefmap.yml` (replace `` 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 ''`, 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 ` 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()`. Check existence with `profile.Has()` or `profile.TryGet(out var t)`. Remove with `profile.Remove()`. @@ -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(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/@/xrefmap.yml` for each package (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.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/Data/Documentation/en/ScriptReference/`, and skip the remaining steps. +2. 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.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//script-reference/`. 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 ''`. 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//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 `` 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, `` 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//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//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//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//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//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.