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/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.)