diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index 0dd67c6..a3904c0 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -24,6 +24,7 @@ "shader-graph" ], "skills": "./skills/", + "hooks": {}, "requires_local_executor": true, "interface": { "displayName": "Unity", diff --git a/.github/README.md b/.github/README.md index 9affb3b..6307a52 100644 --- a/.github/README.md +++ b/.github/README.md @@ -175,6 +175,23 @@ For what each skill covers and how to prompt it, see [About Unity's plugin](https://docs.unity.com/en-us/ai/unity-plugin/about-unity-plugin), or browse the [skills](../skills/using-unity/references/). +## What the plugin adds to a session + +Besides the skill, the plugin adds one sentence at the start of each session. It tells your agent +to load `using-unity` first when you're working on a Unity project or starting a new game project, +so a request that doesn't mention Unity still reaches the right skill. The sentence is added in +every folder, not only in Unity projects. + +How it arrives depends on the agent: + +- **Claude Code**: a `SessionStart` hook in `hooks/hooks.json`. It runs one `echo` command that + prints the sentence, and nothing else. +- **GitHub Copilot CLI**: a plugin rule, `com.github.copilot/rules/unity.mdc`. + `copilot instruction list` shows it under "Plugin instructions". +- **Antigravity**: a plugin rule, `rules/AGENTS.md`. `agy plugin list` counts it in the plugin's + components. +- **Codex** and **Grok**: nothing is added. They find `using-unity` from the skill list. + ## Works best with the Unity CLI Many skills drive your open Unity Editor directly: they create GameObjects, change import settings, run C# in the Editor, and check the result, instead of hand-editing scene and asset files. They do this through the [Unity CLI](https://docs.unity.com/en-us/unity-cli), Unity's command-line tool, which also installs Editors, creates and opens projects, and runs builds and tests. diff --git a/com.github.copilot/rules/unity.mdc b/com.github.copilot/rules/unity.mdc new file mode 100644 index 0000000..bfd2ef3 --- /dev/null +++ b/com.github.copilot/rules/unity.mdc @@ -0,0 +1,5 @@ +--- +description: Unity skills +alwaysApply: true +--- +If you're working on a Unity project, or the user is starting a new game project, always load the using-unity skill first: it has references for every part of game development with Unity and its ecosystem. Check its references against each request, even when the request doesn't explicitly mention Unity. diff --git a/hooks/hooks.json b/hooks/hooks.json new file mode 100644 index 0000000..9a507c6 --- /dev/null +++ b/hooks/hooks.json @@ -0,0 +1,15 @@ +{ + "hooks": { + "SessionStart": [ + { + "matcher": "startup|clear|compact", + "hooks": [ + { + "type": "command", + "command": "echo '{\"hookSpecificOutput\":{\"hookEventName\":\"SessionStart\",\"additionalContext\":\"If you\\u0027re working on a Unity project, or the user is starting a new game project, always load the using-unity skill first: it has references for every part of game development with Unity and its ecosystem. Check its references against each request, even when the request doesn\\u0027t explicitly mention Unity.\"}}'" + } + ] + } + ] + } +} diff --git a/plugin.json b/plugin.json new file mode 100644 index 0000000..9f6bba9 --- /dev/null +++ b/plugin.json @@ -0,0 +1,27 @@ +{ + "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json", + "name": "unity", + "version": "0.1.10-beta", + "description": "Unity's official plugin for coding agents, with curated skills for game development, monetization, and performance optimization.", + "author": { + "name": "Unity Technologies", + "url": "https://unity.com" + }, + "homepage": "https://unity.com", + "repository": "https://github.com/Unity-Technologies/unity-agent-plugin", + "license": "LicenseRef-Unity-Companion-License", + "keywords": [ + "unity", + "gamedev", + "game-development", + "ui-toolkit", + "ugui", + "2d", + "tilemap", + "in-app-purchases", + "monetization", + "localization", + "multiplayer", + "shader-graph" + ] +} diff --git a/rules/AGENTS.md b/rules/AGENTS.md new file mode 100644 index 0000000..91c47f2 --- /dev/null +++ b/rules/AGENTS.md @@ -0,0 +1 @@ +If you're working on a Unity project, or the user is starting a new game project, always load the using-unity skill first: it has references for every part of game development with Unity and its ecosystem. Check its references against each request, even when the request doesn't explicitly mention Unity. diff --git a/scripts/build-codex-zip.mts b/scripts/build-codex-zip.mts index 4bc1aa3..0398f65 100644 --- a/scripts/build-codex-zip.mts +++ b/scripts/build-codex-zip.mts @@ -4,11 +4,26 @@ // node scripts/build-codex-zip.mts writes dist/unity-codex-.zip // // Run it on a clean checkout of merged main, after the version bump. The zip holds one folder, -// `unity`, with the skills (no evals/ or tests/), both manifests, the README, the license and -// the logos the manifests reference. It refuses to build if the manifests disagree on -// the version or drift from scripts/plugin-metadata.json. +// `unity`, with the skills (no evals/ or tests/), the root plugin.json, the Codex manifest, the +// README, the license and the logos the Codex manifest references. It refuses to build if the +// manifests disagree on the name or version, or drift from scripts/plugin-metadata.json. +// +// The directory takes the package's identity (name, version, description, author) from the root +// plugin.json and everything else from .codex-plugin/plugin.json, because the root manifest has +// no extensions.com.openai. Files for other clients stay out: .claude-plugin/, hooks/, rules/ +// and com.github.copilot/. import { execFileSync } from 'node:child_process'; -import { cpSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync } from 'node:fs'; +import { + cpSync, + existsSync, + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + rmSync, + statSync, + writeFileSync, +} from 'node:fs'; import { tmpdir } from 'node:os'; import { basename, join, resolve } from 'node:path'; @@ -22,23 +37,25 @@ execFileSync(process.execPath, [join(root, 'scripts/sync-manifests.mts'), '--che cwd: root, stdio: 'inherit', }); -const manifests = ['.codex-plugin/plugin.json', '.claude-plugin/plugin.json']; +const manifests = ['plugin.json', '.codex-plugin/plugin.json']; +const names = new Set(); for (const file of manifests) { - const { version } = JSON.parse(readFileSync(join(root, file), 'utf8')) as { version: string }; + const { name, version } = JSON.parse(readFileSync(join(root, file), 'utf8')) as { name: string; version: string }; if (version !== meta.version) fail(`${file} is at ${version}, expected ${meta.version}`); + names.add(name); } +if (names.size !== 1) fail(`${manifests.join(' and ')} disagree on the name: ${[...names].join(', ')}`); // 2. Stage the package as /unity. const excluded = new Set(['evals', 'tests', '.DS_Store', 'Thumbs.db']); const contents = [ 'skills', + 'plugin.json', '.codex-plugin', - '.claude-plugin', 'README.md', 'LICENSE.md', 'assets/unity.svg', 'assets/unity-small.svg', - 'assets/unity-tile.svg', // the icon .claude-plugin/plugin.json points to ]; const stage = mkdtempSync(join(tmpdir(), 'unity-codex-')); const pkg = join(stage, 'unity'); @@ -52,6 +69,17 @@ try { }); } + // The Codex manifest sets "hooks": {} so that a git install never picks up hooks/hooks.json, + // which is Claude Code's. The zip has no hooks/ folder, so the key has nothing to switch off + // here, and the plugin directory takes no plugins with lifecycle hooks. Leave it out, so the + // uploaded manifest declares none. + const codexManifest = join(pkg, '.codex-plugin/plugin.json'); + const { hooks, ...packed } = JSON.parse(readFileSync(codexManifest, 'utf8')) as Record; + if (hooks !== undefined && JSON.stringify(hooks) !== '{}') { + fail('.codex-plugin/plugin.json declares hooks; the plugin directory takes no plugins with lifecycle hooks'); + } + writeFileSync(codexManifest, `${JSON.stringify(packed, null, 2)}\n`); + // 3. Check what was staged before zipping it. const skills = readdirSync(join(pkg, 'skills')).filter((d) => existsSync(join(pkg, 'skills', d, 'SKILL.md')), diff --git a/scripts/plugin-metadata.json b/scripts/plugin-metadata.json index 00b4c61..531e2af 100644 --- a/scripts/plugin-metadata.json +++ b/scripts/plugin-metadata.json @@ -21,5 +21,6 @@ "localization", "multiplayer", "shader-graph" - ] + ], + "nudge": "If you're working on a Unity project, or the user is starting a new game project, always load the using-unity skill first: it has references for every part of game development with Unity and its ecosystem. Check its references against each request, even when the request doesn't explicitly mention Unity." } diff --git a/scripts/sync-manifests.mts b/scripts/sync-manifests.mts index 41f961c..1dc694e 100644 --- a/scripts/sync-manifests.mts +++ b/scripts/sync-manifests.mts @@ -8,7 +8,11 @@ // To release, change "version" in plugin-metadata.json and run the script without --check. // Platform-only fields (descriptions, the Codex interface block, Antigravity prompts) stay in // each manifest and are not touched. -import { readFileSync, writeFileSync } from 'node:fs'; +// +// It also writes the session-start nudge ("nudge" in plugin-metadata.json) into the three files +// that deliver it, so they always carry the same sentence. See `nudgeFiles` below. +import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { dirname } from 'node:path'; type Json = string | number | boolean | null | Json[] | { [key: string]: Json }; type JsonObject = { [key: string]: Json }; @@ -21,6 +25,7 @@ interface Metadata { license: string; category: string; keywords: string[]; + nudge: string; } interface Marketplace extends JsonObject { @@ -34,6 +39,14 @@ const shared = ['version', 'author', 'homepage', 'repository', 'license', 'keywo // Each target names a manifest and where each shared key lives in it. const targets: { file: string; set: (manifest: JsonObject) => void }[] = [ { file: '.claude-plugin/plugin.json', set: (m) => assign(m, shared) }, + { + // The Agent Plugins manifest at the plugin root. Copilot CLI reads com.github.copilot/ only + // when it exists, Grok reads it before .claude-plugin/plugin.json, and OpenAI's plugin + // directory takes the package's identity from it. It has no extensions.com.openai, so + // Codex and the directory still read their settings from .codex-plugin/plugin.json. + file: 'plugin.json', + set: (m) => assign(m, shared), + }, { file: '.codex-plugin/plugin.json', set: (m) => { @@ -107,6 +120,63 @@ for (const { file, set } of targets) { else writeFileSync(file, after); } +// The session-start nudge: one sentence telling the agent to open using-unity first, delivered +// in each client's own form. +// hooks/hooks.json Claude Code: a SessionStart hook prints it as additionalContext. +// The matcher leaves out resume, where the saved text is replayed. +// com.github.copilot/rules/unity.mdc Copilot CLI: an always-on plugin rule. +// rules/AGENTS.md Antigravity: an always-on plugin rule. +// Codex and Grok get none. A Codex plugin hook needs the user's approval again after every +// plugin update, so .codex-plugin/plugin.json sets "hooks": {} to keep Codex from picking up +// hooks/hooks.json. Grok runs hooks/hooks.json and ignores what a SessionStart hook prints. +const nudgeFiles: { file: string; content: string }[] = [ + { + file: 'hooks/hooks.json', + content: `${JSON.stringify( + { + hooks: { + SessionStart: [ + { matcher: 'startup|clear|compact', hooks: [{ type: 'command', command: nudgeCommand(meta.nudge) }] }, + ], + }, + }, + null, + 2, + )}\n`, + }, + { + // Copilot CLI lists the rule only with a description and alwaysApply: true, in a .mdc file. + file: 'com.github.copilot/rules/unity.mdc', + content: `---\ndescription: Unity skills\nalwaysApply: true\n---\n${meta.nudge}\n`, + }, + { file: 'rules/AGENTS.md', content: `${meta.nudge}\n` }, +]; + +// The hook command runs in sh, Git Bash or PowerShell, whichever the client picks on the +// user's machine, with no program or file it could depend on. A single-quoted `echo` is the +// one form all of them print unchanged. An apostrophe would end the quoting, so it is written +// as the JSON escape \u0027, which the client decodes. +function nudgeCommand(text: string): string { + if (/[\\"\r\n]/.test(text)) { + throw new Error( + '"nudge" in scripts/plugin-metadata.json has a backslash, a double quote or a line break. ' + + 'Shells disagree on how `echo` prints those, so the hook would break in some of them. Reword it.', + ); + } + const output = JSON.stringify({ hookSpecificOutput: { hookEventName: 'SessionStart', additionalContext: text } }); + return `echo '${output.replaceAll("'", '\\u0027')}'`; +} + +for (const { file, content } of nudgeFiles) { + const before = existsSync(file) ? readFileSync(file, 'utf8').replace(/\r\n/g, '\n') : null; + if (before === content) continue; + if (check) drifted.push(file); + else { + mkdirSync(dirname(file), { recursive: true }); + writeFileSync(file, content); + } +} + // The sample `codex plugin list`, `agy plugin list` and `copilot plugin list` output in the // README shows the version. Only those three lines are matched, so other version numbers in // the README are left alone. diff --git a/skills/using-unity/SKILL.md b/skills/using-unity/SKILL.md index 80d5761..81fa1fc 100644 --- a/skills/using-unity/SKILL.md +++ b/skills/using-unity/SKILL.md @@ -21,7 +21,7 @@ A skill's own files are in its folder, `references//`. When the skill give A skill may tell you to use, load or check for another skill by name, for example "use the `unity-cli` skill" or "check that `ui` is in your client's skills". Every skill in the index below is installed with this one, though only `using-unity` is listed in your client's skills. Treat each of them as available: when a skill names one, read its file from the index and follow it, and don't offer to install it. Where a skill's files mention its `SKILL.md`, that is its `.md` file here. -## Index (33 skills, A to Z) +## Index (34 skills, A to Z) - **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` @@ -46,6 +46,7 @@ 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` +- **project-auditor-fixes**: Runs a Project Auditor scan on a Unity project and fixes the reported issues in small, reviewable batches. Use when asked to audit a Unity project and fix the code, asset or settings issues Project Auditor finds. File: `references/project-auditor-fixes/project-auditor-fixes.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 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` diff --git a/skills/using-unity/references/project-auditor-fixes/SECURITY.md b/skills/using-unity/references/project-auditor-fixes/SECURITY.md new file mode 100644 index 0000000..570d7f1 --- /dev/null +++ b/skills/using-unity/references/project-auditor-fixes/SECURITY.md @@ -0,0 +1,16 @@ +# Security notes: project-auditor-fixes + +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 fixing Project Auditor issues. 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/project-auditor-fixes/project-auditor-fixes.md b/skills/using-unity/references/project-auditor-fixes/project-auditor-fixes.md new file mode 100644 index 0000000..80ac39d --- /dev/null +++ b/skills/using-unity/references/project-auditor-fixes/project-auditor-fixes.md @@ -0,0 +1,156 @@ +--- +name: project-auditor-fixes +description: "Runs a Project Auditor scan on a Unity project and fixes the reported issues in small, reviewable batches. Use when asked to audit a Unity project and fix the code, asset or settings issues Project Auditor finds." +--- + +Using Project Auditor +Project Auditor carries out a static analysis scan of the Unity Project and reports a list of CSV issues that may be fixed. Trigger, poll, read. + +## 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 + +The docs location depends on the project's Unity version, because Project Auditor is part of the Editor from Unity 6000.4, and a separate package (`com.unity.project-auditor`) in earlier versions. Check the Unity version first: + +- **Unity 6000.4 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 `en/Manual/project-auditor` folder. Otherwise the docs pages are online at `https://docs.unity.com/en-us/engine//manual/analysis/project-auditor.md`. docs.unity.com has no 6000.4 pages, so for 6000.4 use `https://docs.unity3d.com/6000.4/Documentation/Manual/project-auditor/` instead. +- **Earlier versions**: The docs pages are local markdown conversions of the Unity Manual, stored at `/Library/PackageCache/com.unity.project-auditor@*/`. 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 `https://docs.unity3d.com/Packages/com.unity.project-auditor@/manual/` instead. + +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. + +Read the Unity major.minor from `ProjectSettings/ProjectVersion.txt` (for example `6000.5` from `6000.5.0f1`, because the full build number gives a 404), and each package's major.minor from `Packages/packages-lock.json` (for example `1.0` for `com.unity.project-auditor`). + +- [Project Auditor introduction](https://docs.unity.com/en-us/engine//manual/analysis/project-auditor/introduction.md) — local `project-auditor/project-auditor-introduction.html`, package `project-auditor-introduction.md`: the issue areas Project Auditor reports, and the window. +- [Analyze your project](https://docs.unity.com/en-us/engine//manual/analysis/project-auditor/analyze-project.md) — local `project-auditor/analyze-project.html`, package `analyze-project.md`: run an analysis, install the rules package, load reports. +- [Project issues introduction](https://docs.unity.com/en-us/engine//manual/analysis/project-auditor/project-issues/introduction.md) — local `project-auditor/project-issues-introduction.html`, package `project-issues-introduction.md`: common project issues and resources for fixing them. +- [Domain reloading issues](https://docs.unity.com/en-us/engine//manual/analysis/project-auditor/project-issues/domain-reloading-issues.md) — local `project-auditor/domain-reloading-issues.html`, package `domain-reloading-issues.md`: how domain reloading affects your project, and code fixes. + +### API reference + +The Project Auditor API is `Unity.ProjectAuditor.Editor`. Fixes can also change any Engine API (`UnityEngine`/`UnityEditor`) the reported code uses. In Unity 6000.4 and later, both are 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. + +In versions earlier than 6000.4, `Unity.ProjectAuditor.Editor` is part of the `com.unity.project-auditor` package and is versioned by package version. Read the version from `Packages/packages-lock.json`, fetch and cache `https://docs.unity3d.com/Packages/com.unity.project-auditor@/xrefmap.yml`, and grep it locally for a class or method instead of refetching per lookup. Don't read the whole file. + +## Procedure + +1. Get the project context: the Unity version from `ProjectSettings/ProjectVersion.txt`, and the `com.unity.project-auditor` or `com.unity.project-auditor-rules` version from `Packages/packages-lock.json`. If a value is missing, assume the latest Unity 6 version and the latest package version, name that assumption in your report, and carry on. If there's no project or Editor you can run the scan in, give the user the steps below for their project instead of stopping. +2. Read the [docs pages](#full-topic-map) for the issue types you intend to fix. +3. Check the [Prerequisites](#prerequisites), then follow [Best Practice](#best-practice) and the [Recipe](#recipe). +4. Run the test case again and compare it with the result from before your changes. +5. Do the checks in [Final step](#final-step). +6. Give the user the [Final report](#final-report), including which issues you fixed, and whether the checks passed. + +## Prerequisites +To use Project Auditor you'll need the Unity CLI installed - see the unity-cli skill for more details. +Once you have that, the `diagnostics run_audit` and `diagnostics audit_status` commands run Project Auditor checks. + +```bash +unity command diagnostics run_audit # optional: --categories Code,ProjectSetting --output my.csv +unity command diagnostics audit_status # repeat until a terminal status is returned +``` + +`diagnostics audit_status` terminal status are `completed` (with `csvPath` + `issueCount`), `failed`, `unavailable`, and +`interrupted` (a domain reload killed the scan — just re-run `diagnostics run_audit`). Polling is responsive while a +scan compiles assemblies and is busy on the main thread. You can only run one scan at a time: a second `diagnostics run_audit` +returns `busy`. There is no cancel — stop polling to abandon a scan. + +The output CSV has columns: `Category, Severity, Areas, Description, RelativePath, Line, DescriptorId, Recommendation` +(these are diagnostics only, so every row is something to fix; `Recommendation` says how to do it). + +> **Requires Project Auditor plus its rules.** `unavailable` means the Editor has no Project Auditor, +> or it has no analysis rules — in a built-in-module Editor the rules live in the separate +> `com.unity.project-auditor-rules` package (`unity command package add --identifier +> com.unity.project-auditor-rules --confirm true`). Read the `message` field; the command never reports +> an empty `completed` scan that would look like a clean project. + +## Gotchas + +- **`editor set_auto_tick` first.** Without it, recompile and tests can hang while the editor is + unfocused. The package's watchdog relies on the tick loop staying alive. +- **Method reload needs the game running.** `script.methodreload reload` applies to a live + game — enter Editor Play Mode (`unity command editor.playmode start`) first, or run a dev Player. +- **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. +- **Async commands poll.** `recompile`→`recompile_status`, `run_tests --async_tests`→ + `test_status`. Never assume completion from the trigger call's response. +- **Target a specific instance** with `--instance host:port` or `--project-path ` + when more than one is running. + +## Best Practice + +When fixing a list of issues it's best practice to have a test case to make sure things are still working correctly. This might be a particular scene to open and start play mode, or a particular platform to build and run. If this isn’t present and there are no instructions, suggest a test case to the user and ask for confirmation. Run the test case before and after changes to make sure the project is still working. + +As you work, commit your changes in line with the user's version control setup. Wherever possible, commit step-by-step, breaking things down into changes that a user can easily understand. + +## Recipe +1. Make sure the project opens cleanly (with no compile or other errors in the Editor). If there are issues present, check with the user; they may know about them and want to ignore them. Run the test case and make sure you know what state it's in, fixing things if necessary. +2. Check the working tree first. If it has uncommitted changes you didn't make, ask the user how to preserve them (commit, stash or leave them), then create a scoped rollback point (a commit of only your own starting state, or a branch) so the process starts from a known version control state. +3. Open the project in the Unity Editor. Then use Unity CLI to run the audit command. +4. Group the issues by file and by type. +5. Choose a type of issue to work through one group or file at a time. +5.a. Default to fixing settings issues on assets or the projects by type. +5.b. Default to fixing code issues by file and subfolder. +5.c. However, it’s important to fix issues in human manageable and reviewable batches. +5.c.i. Making the same small change across a large number of files (for example, switching a boolean setting across many textures) is probably best done in one commit, or a commit per subfolder. +5.c.ii. When making code changes, make sure the code compiles between each commit. +5.d. Make changes based on the recommendations from Project Auditor. Commit each change once there are no errors in the editor. + +## 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: + +[✓] Created a `ColorChange.cs` script. + +Follow these steps to see the effect: + +1. Drag the script onto a GameObject in the Hierarchy window. +2. Enter Play mode to see the color change effect. +3. Use the `Speed` property in the Inspector window to change the speed the color changes. +``` diff --git a/skills/using-unity/references/unity-pipeline/unity-pipeline.md b/skills/using-unity/references/unity-pipeline/unity-pipeline.md index 9ca4d64..e85b1ef 100644 --- a/skills/using-unity/references/unity-pipeline/unity-pipeline.md +++ b/skills/using-unity/references/unity-pipeline/unity-pipeline.md @@ -5,7 +5,10 @@ description: Controls a Unity Editor or dev Player through the com.unity.pipelin # Unity Pipeline (agent control) -Invoke commands with `unity command [args]`. `unity command` lists the command +Invoke commands with `unity command [args]`, and pass `--caller plugin +--skill ` on every `unity command` invocation. `` is the skill whose instructions +produced the call, so a task skill that sends you here passes its own name rather than +`unity-pipeline`. The flags only label the call. `unity command` lists the command groups, `unity command ` one group's commands, and `--query ` filters by name, description or tag. Two servers exist: **Editor** (`7800-7849`, auto-starts with the editor) and **Runtime** (`7900-7949`, only in a dev Player build). @@ -129,10 +132,10 @@ a 15–20s recompile. # 1. Write the builder OUTSIDE Assets/ (so the write triggers no asset import / domain reload), # e.g. AgentScripts/Build.cs: public static class Build { public static int All() { ... } } # 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 +unity command script run --caller plugin --skill unity-pipeline --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 # compile-only check: diagnostics, nothing loaded or executed -unity command script run --file AgentScripts/Build.cs --entry Build.All --args '[3, "Green"]' +unity command script run --caller plugin --skill unity-pipeline --file AgentScripts/Build.cs --dry-run # compile-only check: diagnostics, nothing loaded or executed +unity command script run --caller plugin --skill unity-pipeline --file AgentScripts/Build.cs --entry Build.All --args '[3, "Green"]' ``` Rules of thumb: 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 e6066d1..f6b88e0 100644 --- a/skills/using-unity/references/urp-postprocessing/references/code-templates.md +++ b/skills/using-unity/references/urp-postprocessing/references/code-templates.md @@ -27,8 +27,11 @@ var profile = UnityEngine.ScriptableObject.CreateInstance() only creates the component in memory: also store it in the asset +// with AddObjectToAsset, or the override is gone after the next Editor restart or asset reload. var bloom = profile.Add(); +UnityEditor.AssetDatabase.AddObjectToAsset(bloom, profile); bloom.threshold.overrideState = true; bloom.threshold.value = 0.9f; bloom.intensity.overrideState = true; @@ -37,16 +40,22 @@ bloom.scatter.overrideState = true; bloom.scatter.value = 0.7f; var tonemapping = profile.Add(); +UnityEditor.AssetDatabase.AddObjectToAsset(tonemapping, profile); tonemapping.mode.overrideState = true; tonemapping.mode.value = UnityEngine.Rendering.Universal.TonemappingMode.ACES; var volumeObj = new UnityEngine.GameObject("Global Volume"); var volume = volumeObj.AddComponent(); volume.isGlobal = true; -volume.profile = profile; +// sharedProfile references the asset. The profile setter only fills the Volume's runtime slot, +// which is not saved, so the reloaded scene would show the Volume with no profile. +volume.sharedProfile = profile; UnityEditor.Undo.RegisterCreatedObjectUndo(volumeObj, "Create Global Volume"); +UnityEditor.EditorUtility.SetDirty(bloom); +UnityEditor.EditorUtility.SetDirty(tonemapping); UnityEditor.EditorUtility.SetDirty(profile); +UnityEditor.EditorUtility.SetDirty(volume); UnityEditor.AssetDatabase.SaveAssets(); return "Created Global Volume with Bloom and ACES Tonemapping."; @@ -95,11 +104,19 @@ if (volumeObj != null && volumeObj.TryGetComponent && volume.sharedProfile != null) { var profile = volume.sharedProfile; - if (profile.TryGet(out var bloom)) - { - bloom.intensity.overrideState = true; - bloom.intensity.value = 2f; - } + if (!profile.TryGet(out var bloom)) + bloom = profile.Add(); + + // TryGet only reads the in-memory list, so finding the override doesn't mean it is saved. + // Store it in the asset if it isn't yet: this also repairs a profile written by code that + // skipped AddObjectToAsset. + if (!UnityEditor.AssetDatabase.IsSubAsset(bloom)) + UnityEditor.AssetDatabase.AddObjectToAsset(bloom, profile); + + bloom.intensity.overrideState = true; + bloom.intensity.value = 2f; + + UnityEditor.EditorUtility.SetDirty(bloom); UnityEditor.EditorUtility.SetDirty(profile); // SetDirty only marks the asset. Without this the edit is in memory only: it reads back // correctly for the rest of the session and is lost when the session ends. @@ -130,6 +147,8 @@ UnityEditor.EditorUtility.SetDirty(target); // SetDirty marks; it does not write. Persist according to what `target` is, or the change is // lost at session end even though every read-back looks correct: // an asset (Volume Profile, URP Asset) -> UnityEditor.AssetDatabase.SaveAssets(); +// (persists edits to existing overrides; an override +// newly added with Add() also needs AddObjectToAsset) // a component in a scene -> MarkSceneDirty(target.gameObject.scene) and tell // the user the scene needs saving UnityEditor.Undo.FlushUndoRecordObjects(); // force the snapshot out now diff --git a/skills/using-unity/references/urp-postprocessing/urp-postprocessing.md b/skills/using-unity/references/urp-postprocessing/urp-postprocessing.md index 0804b62..e8a1858 100644 --- a/skills/using-unity/references/urp-postprocessing/urp-postprocessing.md +++ b/skills/using-unity/references/urp-postprocessing/urp-postprocessing.md @@ -141,6 +141,12 @@ foreach (var vol in volumes) if (profile == null) { report.AppendLine($"Warning: Volume '{vol.name}' has no profile assigned."); continue; } if (profile.components.Count == 0) report.AppendLine($"Warning: Volume '{vol.name}' profile has no overrides."); + // An override added to a profile asset without AddObjectToAsset is in memory only: it shows + // up now but is gone after the next Editor restart. + if (UnityEditor.EditorUtility.IsPersistent(profile)) + foreach (var c in profile.components) + if (c != null && !UnityEditor.AssetDatabase.IsSubAsset(c)) + report.AppendLine($"Warning: override '{c.GetType().Name}' on profile '{profile.name}' is not saved in the asset. Call AssetDatabase.AddObjectToAsset(component, profile), then SaveAssets()."); } // Return the findings: logs land in the Editor console, the returned value comes back to you @@ -191,13 +197,14 @@ using UnityEngine.Rendering.Universal; // Bloom, Tonemapping, ColorAdjustments, | `UnityEngine.Rendering.PostProcessing` | `UnityEngine.Rendering.Universal` | | `profile.GetSetting()` | `profile.TryGet(out var t)` (returns bool) | | `profile.AddSettings()` | `profile.Add()` (returns T; throws if already exists — check `profile.Has()` first) | -| `volume.sharedProfile` (to modify at runtime) | `volume.profile` (auto-clones the asset into an instance) | -| `VolumeManager.instance.stack.GetComponent()` | `volume.profile.TryGet(out var t)` | +| `volume.profile = asset` (in Editor code) | `volume.sharedProfile = asset` (references the asset; the `profile` slot is a runtime instance the scene never saves) | +| `VolumeManager.instance.stack.GetComponent()` | `volume.sharedProfile.TryGet(out var t)` | ### Key Facts - **`overrideState = true`** is required on every `VolumeParameter` you set. The volume system skips parameters where `overrideState` is `false`. This is the #1 scripting mistake. - **`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. +- **On a profile asset in the Editor, `Add()` alone is in memory only.** Also call `UnityEditor.AssetDatabase.AddObjectToAsset(component, profile)` before `SaveAssets()`, or the override is gone after the next Editor restart. A runtime `volume.profile` instance doesn't need it. ## Step 7. Debugging Checklist @@ -205,7 +212,9 @@ When post-processing isn't working, check in order: 1. `cam.TryGetComponent(out var data)` succeeds and `data.renderPostProcessing` is `true`? 2. Volume exists in scene with a non-null `profile` (or `sharedProfile`) assigned? -3. Overrides added via `profile.Add()` AND `overrideState = true` on each property you set? +3. Overrides added via `profile.Add()` AND `overrideState = true` on each property you set? On a profile asset, is each override also a sub-asset (`AssetDatabase.AddObjectToAsset`)? + - The effect worked but vanished after Play Mode exit or an Editor restart: the override was never stored in the asset. `AssetDatabase.LoadAllAssetsAtPath(profilePath)` must return the profile plus one object per override. + - The Volume's profile field shows `None` while the effect still renders: the code assigned `volume.profile` instead of `volume.sharedProfile`. 4. Volume's `GameObject.layer` is included in camera's `data.volumeLayerMask`? (Default mask is layer 0 "Default" only.) 5. `volume.isGlobal = true` (for global), or camera is inside the Volume's trigger `Collider` (for local)? 6. Camera `data.renderType` is `CameraRenderType.Base`, not `Overlay`? (Overlay cameras composite onto the Base camera's output.)