77 game-dev skills for AI coding agents — Godot, Unity, Unreal, Phaser, PixiJS, three.js, Bevy, pygame, LÖVE, Roblox. Portable SKILL.md Agent Skills (the format Anthropic launched as Claude Skills), with a router that loads the right skill for your engine and task. Runs in Claude Code, Cursor, Kiro, Codex, Copilot, Gemini CLI and more.
Python agent-skillsai-agentsantigravityawesome-listclaude-codeclinecodexcursorgame-devgame-developmentgamedevgemini-cligithub-copilotgodotkirooh-my-piskillsunityunrealwindsurf
feat(unity): add 8 Unity 6 skills
AbhishekBarali1213ac22e8041
diff --git a/skills/unity/unity-animation/SKILL.md b/skills/unity/unity-animation/SKILL.mdnew file mode 100644index 0000000..4dc94fb--- /dev/null+++ b/skills/unity/unity-animation/SKILL.md@@ -0,0 +1,129 @@+---+name: unity-animation+description: >+ Drive Unity 6 character animation with Animator Controllers: states, transitions,+ parameters, blend trees, animation layers, and humanoid Avatar IK. Use when wiring an+ Animator, setting parameters from script (SetFloat/SetBool/SetTrigger), building blend+ trees, or when the user mentions Animator, Mecanim, state machine, blend tree, or .controller.+license: Apache-2.0+compatibility: Unity 6 (6000.0 LTS); Animator / Mecanim, humanoid Avatars+metadata:+ engine: unity+ category: unity+ difficulty: intermediate+---++# Unity Animation (Animator / Mecanim)++Control animation state with Unity 6's `Animator` and Animator Controllers: parameters,+transitions, blend trees, layers, and humanoid IK. Targets **Unity 6 (6000.0 LTS)**.++## When to use++- Use when connecting animation clips into a state machine, driving them from script via+ parameters, blending locomotion (idle→walk→run), layering an upper-body action over+ movement, or adding foot/hand IK on a humanoid rig.+- Use when the project has `*.controller` (Animator Controller) and `*.anim` assets, or a+ rigged model with an Avatar.++**When *not* to use:** simple non-skeletal value tweens (UI fades, position lerps) are better+done with a tween/coroutine — see `unity-csharp-scripting`. Timeline cutscenes are a separate+tool. 2D sprite frame animation also uses the Animator but with sprite keyframes.++## Core workflow++1. **Add an `Animator`** to the model and assign an Animator Controller; for a humanoid model,+ set its rig to **Humanoid** so it has an Avatar (enables retargeting and IK).+2. **Define parameters** on the controller — `Float` (Speed), `Bool` (IsGrounded), `Int`,+ `Trigger` (Jump) — and states with transitions whose *conditions* read those parameters.+3. **Set parameters from script**, never poke states directly: `SetFloat`, `SetBool`,+ `SetInteger`, `SetTrigger`. The state machine resolves transitions for you.+4. **Blend continuous motion with a Blend Tree** (one `Float` like Speed drives idle↔walk↔run)+ instead of many discrete states + transitions.+5. **Layer additive/override motion** (e.g. an upper-body "aim" layer with an Avatar Mask) and+ control its `layerWeight`.+6. **Verify** in the Animator window during Play mode — the live state highlights and parameter+ values update, so you can see exactly which transition fired (or didn't).++## Patterns++### 1. Drive locomotion + a one-shot action from script++```csharp+using UnityEngine;++[RequireComponent(typeof(Animator))]+public class CharacterAnim : MonoBehaviour+{+ private Animator _anim;+ // Cache parameter hashes — faster and typo-proof vs string lookups every frame.+ private static readonly int Speed = Animator.StringToHash("Speed");+ private static readonly int IsGrounded= Animator.StringToHash("IsGrounded");+ private static readonly int Jump = Animator.StringToHash("Jump");++ private void Awake() => _anim = GetComponent<Animator>();++ public void Tick(float planarSpeed, bool grounded)+ {+ _anim.SetFloat(Speed, planarSpeed); // drives a 1D blend tree (idle/walk/run)+ _anim.SetBool(IsGrounded, grounded); // gates a falling/landing transition+ }++ public void DoJump() => _anim.SetTrigger(Jump); // fire-and-forget; auto-resets after use+}+```++### 2. Smooth a noisy input into a blend parameter++```csharp+// dampTime smooths Speed so the blend tree doesn't snap; great for analog sticks.+_anim.SetFloat(Speed, targetSpeed, 0.1f /* dampTime */, Time.deltaTime);+```++### 3. Play / cross-fade a state directly (bypassing parameter conditions)++```csharp+// Useful for hit reactions where you want an immediate, explicit transition.+_anim.CrossFade("Hit", 0.1f); // blend over 0.1s normalized+// Or jump instantly: _anim.Play("Hit");+```++### 4. Wait until the current state finishes++```csharp+private System.Collections.IEnumerator AfterAttack()+{+ var info = _anim.GetCurrentAnimatorStateInfo(0); // layer 0+ yield return new WaitForSeconds(info.length); // approximate clip length+ // ...follow-up logic+}+```++## Pitfalls++- **`SetTrigger` missed or "sticks"** — triggers are consumed by the next satisfied transition+ and auto-reset; if no transition consumes it, it can fire later unexpectedly. Use+ `ResetTrigger` to clear, or prefer a `Bool` when the condition is a sustained state.+- **String parameter typos fail silently** — a misspelled name just does nothing. Use+ `Animator.StringToHash` and cache the int hashes.+- **Transition feels laggy** — `Has Exit Time` makes the transition wait for the clip to reach+ a normalized time. Uncheck it for responsive, condition-driven transitions (jump, hit).+- **Character slides or won't move** — `Apply Root Motion` is on but your code also moves the+ transform (or vice versa). Decide: root motion *or* scripted movement, not both.+- **Upper-body layer overrides the whole body** — set the layer's Blend mode (Override vs+ Additive), assign an Avatar Mask, and tune `layerWeight` (0–1).+- **IK does nothing** — IK only applies inside `OnAnimatorIK`, requires "IK Pass" enabled on+ the layer, and needs a Humanoid Avatar.++## References++- For **blend trees** (1D vs 2D Freeform/Directional), **animation layers + Avatar Masks**,+ and **humanoid IK** (`OnAnimatorIK`, `SetIKPositionWeight`, `SetIKPosition`, look-at), read+ `references/blend-trees-and-ik.md`.+- Primary docs: Unity Manual "Animation" section and `ScriptReference/Animator`.++## Related skills++- `unity-csharp-scripting` — the MonoBehaviour and coroutine timing used above.+- `unity-physics` — moving the body that the animation visualises.+- `game-ai` — deciding *when* to play which animation state.diff --git a/skills/unity/unity-animation/references/blend-trees-and-ik.md b/skills/unity/unity-animation/references/blend-trees-and-ik.mdnew file mode 100644index 0000000..e0865f7--- /dev/null+++ b/skills/unity/unity-animation/references/blend-trees-and-ik.md@@ -0,0 +1,83 @@+# Blend trees, layers & humanoid IK (Unity 6)++Depth for `unity-animation`. Verified against the Unity Manual Animation section and+`ScriptReference/Animator`.++## Blend trees++A Blend Tree blends several clips by one or two `Float` parameters, so continuous motion+(idle → walk → run, or 8-direction movement) is one node instead of many states.++- **1D** — one parameter (e.g. `Speed`). Place clips along the axis (0 idle, 2 walk, 6 run);+ the tree cross-fades by where the parameter sits.+- **2D Simple Directional** — clips at distinct directions (forward, back, strafe).+- **2D Freeform Directional / Cartesian** — arbitrary clip placement in a 2D field+ (`MoveX`, `MoveY`); Freeform Cartesian suits non-directional pairs (speed × turn).++Drive it from script exactly like any float parameter, ideally damped:++```csharp+_anim.SetFloat("Speed", speed, 0.1f, Time.deltaTime); // dampTime smooths the blend+_anim.SetFloat("MoveX", moveX);+_anim.SetFloat("MoveY", moveY);+```++Tip: keep blend thresholds matched to the clips' real root speed so feet don't slide.++## Animation layers + Avatar Masks++Layers let an upper-body action (aim, throw) play over a base locomotion layer.++- Each layer has a **weight** (0–1) and a **Blend mode**: `Override` (replaces) or `Additive`+ (adds on top of the base pose).+- An **Avatar Mask** restricts a layer to selected bones (e.g. spine + arms), so the legs keep+ walking while the arms aim.++```csharp+int aimLayer = _anim.GetLayerIndex("UpperBody");+_anim.SetLayerWeight(aimLayer, isAiming ? 1f : 0f); // fade the layer in/out+```++## Humanoid IK (`OnAnimatorIK`)++IK adjusts hands/feet/look toward targets *after* the animation pose is sampled. Requirements:+Humanoid Avatar, and **IK Pass** enabled on the layer.++```csharp+[SerializeField] private Transform lookTarget, rightHandTarget;++// Called by the Animator once per frame, per layer, when IK Pass is on.+private void OnAnimatorIK(int layerIndex)+{+ if (lookTarget)+ {+ _anim.SetLookAtWeight(1f); // overall look-at weight+ _anim.SetLookAtPosition(lookTarget.position);+ }+ if (rightHandTarget)+ {+ _anim.SetIKPositionWeight(AvatarIKGoal.RightHand, 1f); // 0..1 blend toward target+ _anim.SetIKRotationWeight(AvatarIKGoal.RightHand, 1f);+ _anim.SetIKPosition(AvatarIKGoal.RightHand, rightHandTarget.position);+ _anim.SetIKRotation(AvatarIKGoal.RightHand, rightHandTarget.rotation);+ }+}+```++`AvatarIKGoal` values: `LeftFoot`, `RightFoot`, `LeftHand`, `RightHand`. Set the weight back+toward 0 to release the IK smoothly.++### Foot IK for sloped ground++- Enable **Foot IK** on the locomotion states.+- Raycast down from each foot, then `SetIKPosition`/`SetIKRotation` to the surface point and+ normal so feet plant on slopes instead of clipping or floating.++## Gotchas++- IK calls outside `OnAnimatorIK` are ignored.+- `SetLookAtWeight` has extra body/head/eyes/clamp parameters — the single-arg overload is a+ shortcut for the common case.+- Layer weights and IK weights are not auto-reset; lerp them toward 0 when disengaging or the+ pose stays stuck.+- Additive layers need a reference pose set on the clip's import settings, or they drift.diff --git a/skills/unity/unity-build-pipeline/SKILL.md b/skills/unity/unity-build-pipeline/SKILL.mdnew file mode 100644index 0000000..9590b58--- /dev/null+++ b/skills/unity/unity-build-pipeline/SKILL.md@@ -0,0 +1,128 @@+---+name: unity-build-pipeline+description: >+ Build and ship Unity 6 players: build settings and scenes, player/quality settings, the+ IL2CPP vs Mono scripting backend, managed code stripping, scripted BuildPipeline.BuildPlayer,+ and CI/headless builds. Use when configuring or automating a build, choosing a scripting+ backend, shrinking build size, or when the user mentions Unity build, player settings,+ IL2CPP, code stripping, or Addressables.+license: Apache-2.0+compatibility: Unity 6 (6000.0 LTS); UnityEditor.BuildPipeline. Addressables is a separate package.+metadata:+ engine: unity+ category: unity+ difficulty: intermediate+---++# Unity Build Pipeline++Configure, script, and automate Unity 6 player builds: scenes, platform target, scripting+backend, stripping, and headless/CI builds. Targets **Unity 6 (6000.0 LTS)**.++## When to use++- Use when setting up Build Settings/Profiles, choosing a platform and scripting backend+ (Mono vs IL2CPP), reducing build size with managed stripping, scripting a repeatable build+ with `BuildPipeline.BuildPlayer`, or wiring a CI/headless build.+- Use when the project has `ProjectSettings/EditorBuildSettings.asset` or a CI build script.++**When *not* to use:** authoring a CI service config end-to-end is DevOps; this skill covers+the Unity-side build API and settings. Console/platform certification specifics are+platform-NDA territory. Storefront submission → `steam-publish` / `itch-publish`.++## Core workflow++1. **List the scenes to build** (File → Build Profiles/Settings → Scene List, or+ `EditorBuildSettings.scenes`). Only listed, enabled scenes ship; scene 0 is the start scene.+2. **Pick the platform target** and switch the active build target if needed+ (`BuildTarget` / `EditorUserBuildSettings`).+3. **Choose the scripting backend** (Player Settings): **Mono** (fast iteration, desktop) vs+ **IL2CPP** (AOT C++; required for many platforms, better perf, harder to reverse). IL2CPP+ needs the platform's C++ toolchain installed.+4. **Tune size/perf:** set Managed Stripping Level (Disabled → Minimal → Low → Medium → High)+ and protect reflection-only code with a `link.xml`. Set Quality Settings per platform.+5. **Script the build** with `BuildPipeline.BuildPlayer(BuildPlayerOptions)` and **inspect the+ returned `BuildReport`** — a non-`Succeeded` result must fail your pipeline.+6. **Run headless** for CI with `-batchmode -quit -executeMethod`, and check the exit code.+7. **Verify** the actual output runs (launch the player), not just that the build returned+ without throwing.++## Patterns++### 1. Scripted build with a result check++```csharp+using UnityEditor;+using UnityEditor.Build.Reporting;+using UnityEngine;++public static class BuildScript+{+ [MenuItem("Build/Windows x64")]+ public static void BuildWindows()+ {+ var options = new BuildPlayerOptions+ {+ scenes = new[] { "Assets/Scenes/Main.unity", "Assets/Scenes/Level1.unity" },+ locationPathName = "Builds/Windows/Game.exe",+ target = BuildTarget.StandaloneWindows64,+ options = BuildOptions.None, // add BuildOptions.Development for a dev build+ };++ BuildReport report = BuildPipeline.BuildPlayer(options);+ BuildSummary summary = report.summary;++ if (summary.result != BuildResult.Succeeded)+ throw new System.Exception($"Build failed: {summary.totalErrors} errors");+ Debug.Log($"Build OK: {summary.totalSize} bytes in {summary.totalTime}");+ }+}+```++### 2. Headless / CI invocation++```bash+# Exit code is 0 on success; -quit ensures the editor closes; -nographics for build servers.+Unity -batchmode -quit -nographics \+ -projectPath "/path/to/Project" \+ -executeMethod BuildScript.BuildWindows \+ -logFile -+```++### 3. Protect stripped code with `link.xml`++```xml+<!-- Assets/link.xml — keep types the linker can't see are used (reflection, JSON, plugins). -->+<linker>+ <assembly fullname="MyGameRuntime" preserve="all"/>+</linker>+```++## Pitfalls++- **A scene loads in the Editor but is missing in the build** — it isn't in the Build Settings+ scene list (or is disabled). `SceneManager.LoadScene` only sees listed scenes.+- **IL2CPP build fails on a fresh machine** — the platform C++ toolchain (e.g. Windows build+ tools, Android NDK) isn't installed. Mono has no such requirement.+- **`MissingMethodException`/`TypeLoadException` only in the build** — managed stripping removed+ reflection-only code. Lower the stripping level or add a `link.xml` preserve entry.+- **Treating "BuildPlayer returned" as success** — always check `BuildReport.summary.result`;+ it can return with errors.+- **Addressables content is stale/missing** — Addressables (`com.unity.addressables`) need a+ *separate* content build (Build → Addressables) and a profile pointing at the right load+ path; a player build alone doesn't rebuild them.+- **Shipping a Development build** — `BuildOptions.Development` enables the profiler/debugging+ and is slower; use `BuildOptions.None` for release.++## References++- For a complete **multi-platform CI build script** (target switching, version stamping,+ argument parsing, exit codes) and an Addressables content-build call, read+ `references/ci-build-script.md`.+- Primary docs: `ScriptReference/BuildPipeline.BuildPlayer`, Unity Manual build sections+ (player settings, managed code stripping).++## Related skills++- `steam-publish` / `itch-publish` — distributing the player you just built.+- `unity-csharp-scripting` — editor scripting conventions used by build scripts.diff --git a/skills/unity/unity-build-pipeline/references/ci-build-script.md b/skills/unity/unity-build-pipeline/references/ci-build-script.mdnew file mode 100644index 0000000..713862f--- /dev/null+++ b/skills/unity/unity-build-pipeline/references/ci-build-script.md@@ -0,0 +1,115 @@+# CI / headless build script (Unity 6)++Depth for `unity-build-pipeline`: a reusable editor build script that takes command-line+arguments, switches platform, stamps a version, and returns a proper exit code. Verified+against `ScriptReference/BuildPipeline.BuildPlayer` and the editor command-line arguments.++## A parameterised build method++```csharp+using System;+using System.Linq;+using UnityEditor;+using UnityEditor.Build.Reporting;+using UnityEngine;++public static class CIBuild+{+ // Invoke with: -executeMethod CIBuild.Run -buildTarget Win64 -out Builds/Game.exe -version 1.2.3+ public static void Run()+ {+ string[] args = Environment.GetCommandLineArgs();++ string targetArg = ArgValue(args, "-buildTarget", "Win64");+ string outPath = ArgValue(args, "-out", "Builds/Game.exe");+ string version = ArgValue(args, "-version", PlayerSettings.bundleVersion);+ bool dev = args.Contains("-dev");++ BuildTarget target = targetArg switch+ {+ "Win64" => BuildTarget.StandaloneWindows64,+ "Mac" => BuildTarget.StandaloneOSX,+ "Linux" => BuildTarget.StandaloneLinux64,+ "Android" => BuildTarget.Android,+ _ => throw new ArgumentException($"Unknown -buildTarget {targetArg}")+ };++ // Switch the active target so the right platform defines/assets are used.+ EditorUserBuildSettings.SwitchActiveBuildTarget(+ BuildPipeline.GetBuildTargetGroup(target), target);++ PlayerSettings.bundleVersion = version; // stamp the version into the player++ var options = new BuildPlayerOptions+ {+ scenes = EnabledScenes(),+ locationPathName = outPath,+ target = target,+ options = dev ? BuildOptions.Development : BuildOptions.None,+ };++ BuildReport report = BuildPipeline.BuildPlayer(options);+ BuildSummary s = report.summary;++ if (s.result == BuildResult.Succeeded)+ {+ Debug.Log($"[CIBuild] OK {version} -> {outPath} ({s.totalSize} bytes)");+ EditorApplication.Exit(0); // explicit success exit code for CI+ }+ else+ {+ Debug.LogError($"[CIBuild] FAILED: {s.totalErrors} errors, result={s.result}");+ EditorApplication.Exit(1); // non-zero fails the pipeline+ }+ }++ private static string[] EnabledScenes() =>+ EditorBuildSettings.scenes.Where(sc => sc.enabled).Select(sc => sc.path).ToArray();++ private static string ArgValue(string[] args, string key, string fallback)+ {+ int i = Array.IndexOf(args, key);+ return (i >= 0 && i + 1 < args.Length) ? args[i + 1] : fallback;+ }+}+```++## Invoking from CI++```bash+# Use -quit so the editor exits; the method itself also calls EditorApplication.Exit for clarity.+Unity -batchmode -nographics \+ -projectPath "$CI_PROJECT_DIR" \+ -executeMethod CIBuild.Run \+ -buildTarget Win64 -out "Builds/Win/Game.exe" -version "1.2.$BUILD_NUMBER" \+ -logFile - || exit 1+```++- Pipe `-logFile -` to stdout so the CI captures the Unity log.+- `EditorApplication.Exit(code)` inside the method is the reliable way to set the exit code;+ `-quit` alone returns 0 even after a logged error.+- Activate the Unity license in batch mode (`-username`/`-password`/`-serial` or a license+ file) as a separate step before building on a clean runner.++## Addressables content build (when used)++```csharp+using UnityEditor.AddressableAssets.Settings;++// Build the Addressables content bundles BEFORE the player build, or runtime loads fail.+public static void BuildContent()+{+ AddressableAssetSettings.BuildPlayerContent(out var result);+ if (!string.IsNullOrEmpty(result.Error))+ throw new Exception($"Addressables build failed: {result.Error}");+}+```++## Gotchas++- `SwitchActiveBuildTarget` can take time and triggers a reimport; do it once per target, not+ per build.+- Reading args via `Environment.GetCommandLineArgs()` includes Unity's own flags — match on+ your custom keys only.+- A build server needs the platform module installed (e.g. IL2CPP toolchain, Android SDK/NDK)+ or the build fails late with a toolchain error.diff --git a/skills/unity/unity-csharp-scripting/SKILL.md b/skills/unity/unity-csharp-scripting/SKILL.mdnew file mode 100644index 0000000..e7c1f7e--- /dev/null+++ b/skills/unity/unity-csharp-scripting/SKILL.md@@ -0,0 +1,144 @@+---+name: unity-csharp-scripting+description: >+ Write Unity 6 C# gameplay scripts: the MonoBehaviour lifecycle+ (Awake/OnEnable/Start/Update/FixedUpdate/LateUpdate), GameObject and component+ access, coroutines, and Inspector serialization. Use when creating or editing .cs+ scripts in a Unity project, or when the user mentions MonoBehaviour, Start/Update,+ GetComponent, SerializeField, coroutines, or "Unity script".+license: Apache-2.0+compatibility: Unity 6 (6000.0 LTS); also valid for 2022 LTS+metadata:+ engine: unity+ category: unity+ difficulty: beginner+---++# Unity C# Scripting (MonoBehaviour)++Write correct, idiomatic gameplay scripts in Unity 6. Get the lifecycle, component+access, serialization, and coroutines right so behaviour is deterministic and the+Inspector stays useful. Targets **Unity 6 (6000.0 LTS)**, C# / .NET Standard 2.1.++## When to use++- Use when authoring or fixing a `MonoBehaviour`: choosing the right lifecycle callback,+ reading/caching components, exposing fields to the Inspector, or running timed logic+ with coroutines.+- Use when the project has `*.cs` files, an `Assembly-CSharp` or `*.asmdef`, and a+ `ProjectSettings/` folder.++**When *not* to use:** moving rigidbodies / collision response → `unity-physics`; reading+player input → `unity-input-system`; shared data assets / config → `unity-scriptableobjects`;+Animator parameters → `unity-animation`. This skill owns the *script lifecycle and C#+plumbing*, not those subsystems.++## Core workflow++1. **Pick the callback by purpose, not habit.** `Awake` (cache references, runs once on+ load), `OnEnable` (subscribe to events), `Start` (init that depends on other objects'+ `Awake`), `Update` (per-frame logic/input polling), `FixedUpdate` (physics), `LateUpdate`+ (camera follow after movement), `OnDisable`/`OnDestroy` (unsubscribe/cleanup).+2. **Cache component lookups in `Awake`** — never call `GetComponent` every frame.+3. **Expose tunables with `[SerializeField] private`**, not public fields, so other code+ can't mutate them but designers can edit them in the Inspector.+4. **Scale per-frame values by `Time.deltaTime`** in `Update` (and `Time.fixedDeltaTime`+ semantics are automatic in `FixedUpdate`).+5. **Use coroutines for time-sequenced logic** (delays, tweens, "do X then wait then Y");+ start them with `StartCoroutine` and stop them deterministically.+6. **Verify in Play mode**: check the Console for null-reference exceptions, confirm values+ in the Inspector update as expected, and watch the Profiler if `Update` is hot.++## Patterns++### 1. Lifecycle + cached components (the canonical skeleton)++```csharp+using UnityEngine;++[RequireComponent(typeof(Rigidbody))] // auto-adds the dependency, prevents null refs+public class PlayerController : MonoBehaviour+{+ [SerializeField] private float moveSpeed = 6f; // editable in Inspector, private in code+ private Rigidbody _rb; // cached, not fetched per frame++ private void Awake() => _rb = GetComponent<Rigidbody>(); // cache once on load++ private void Update()+ {+ // Per-frame, non-physics work. Scale by deltaTime so it is frame-rate independent.+ transform.Rotate(0f, 90f * Time.deltaTime, 0f);+ }++ private void FixedUpdate()+ {+ // Physics work belongs here (fixed timestep). See the unity-physics skill.+ _rb.MovePosition(_rb.position + transform.forward * moveSpeed * Time.fixedDeltaTime);+ }+}+```++### 2. Safe component access with `TryGetComponent`++```csharp+// Avoids allocating a null and is clearer than GetComponent + null check.+if (other.TryGetComponent<Health>(out var health))+ health.Apply(-10);+```++### 3. Serialization that shows up correctly in the Inspector++```csharp+[SerializeField, Range(0f, 1f)] private float volume = 0.8f; // slider+[SerializeField] private string playerName = "Hero"; // private but serialized++[System.Serializable] // REQUIRED for a plain class to serialize/show+public class Stats { public int hp = 100; public int mana = 50; }++[SerializeField] private Stats stats = new(); // nested struct-like data in the Inspector+```++### 4. Coroutines for time-sequenced logic++```csharp+private void Start() => StartCoroutine(FlashThenHide());++private System.Collections.IEnumerator FlashThenHide()+{+ yield return new WaitForSeconds(0.5f); // wait half a second of game time+ GetComponent<Renderer>().enabled = false;+ yield return null; // resume next frame+}+```++## Pitfalls++- **`GetComponent` in `Update`** — it searches every frame and tanks performance. Cache the+ reference in `Awake`/`Start`.+- **Physics in `Update`** — moving a `Rigidbody` with forces or `MovePosition` outside+ `FixedUpdate` causes jitter and timestep-dependent behaviour. Read input in `Update`,+ apply physics in `FixedUpdate`.+- **Relying on `Start` order across objects** — `Start` runs after *all* `Awake`s, but order+ among `Start`s is undefined. Do cross-object wiring in `Start`, self-setup in `Awake`.+- **`public` fields just to show them in the Inspector** — that also lets any script mutate+ them. Use `[SerializeField] private` instead.+- **`gameObject.tag == "Enemy"`** allocates a string and is slower; use+ `gameObject.CompareTag("Enemy")`.+- **Coroutines stop when the GameObject is disabled** — a disabled object's coroutines are+ killed; re-`StartCoroutine` in `OnEnable` if it must survive toggling.+- **`Update` runs before `Start` never happens, but the *first* `Update` can run the same+ frame as `Start`** — guard against not-yet-initialised fields if you split setup oddly.++## References++- For the full event-execution-order table and advanced coroutine patterns (custom+ `CustomYieldInstruction`, stopping by handle, `WaitUntil`/`WaitWhile`), read+ `references/lifecycle-and-coroutines.md`.+- Primary docs: Unity Manual "Event function execution order"+ (`https://docs.unity3d.com/Manual/execution-order.html`) and `ScriptReference/MonoBehaviour`.++## Related skills++- `unity-physics` — `Rigidbody`, collisions, and `FixedUpdate` motion.+- `unity-input-system` — reading player input into these scripts.+- `unity-scriptableobjects` — sharing data/config between scripts without singletons.diff --git a/skills/unity/unity-csharp-scripting/references/lifecycle-and-coroutines.md b/skills/unity/unity-csharp-scripting/references/lifecycle-and-coroutines.mdnew file mode 100644index 0000000..94f768a--- /dev/null+++ b/skills/unity/unity-csharp-scripting/references/lifecycle-and-coroutines.md@@ -0,0 +1,90 @@+# MonoBehaviour lifecycle & coroutines (Unity 6)++Depth for the `unity-csharp-scripting` skill: the full execution order and the coroutine+patterns that don't fit in the main playbook. Verified against the Unity Manual+"Event function execution order" page and `ScriptReference/MonoBehaviour`.++## Execution order (the parts that matter for gameplay)++Per object, the engine calls these in this order:++| Phase | Callback | Runs | Use for |+|-------|----------|------|---------|+| Load | `Awake` | once, when the object loads (even if disabled) | cache `GetComponent`, set up self |+| Enable | `OnEnable` | each time the object/script enables | subscribe to events, re-arm coroutines |+| Init | `Start` | once, before first `Update`, after every `Awake` | wiring that depends on other objects |+| Physics | `FixedUpdate` | every fixed step (default 0.02s) | rigidbody forces, `MovePosition` |+| Physics | `OnTriggerXXX` / `OnCollisionXXX` | during the physics step | collision/trigger response |+| Frame | `Update` | once per rendered frame | input polling, non-physics logic |+| Frame | `LateUpdate` | once per frame, after all `Update`s | camera follow, IK fix-up |+| Disable | `OnDisable` | each time the object/script disables | unsubscribe from events |+| Teardown | `OnDestroy` | once, when destroyed | release native handles, save |++Key consequences:++- `FixedUpdate` may run zero, one, or several times per frame depending on frame rate. Never+ read raw "per frame" input there — read it in `Update`, consume it in `FixedUpdate`.+- All `Awake` calls finish before any `Start`. Order *among* `Awake`s (and among `Start`s) is+ undefined unless you set a Script Execution Order in Project Settings.+- `OnEnable` runs after `Awake` on first enable, then again on every re-enable. Pair every+ `OnEnable` subscription with an `OnDisable` unsubscription to avoid duplicate handlers.++## Coroutine yield instructions++```csharp+yield return null; // resume at the start of the next frame+yield return new WaitForSeconds(2f); // wait 2s of scaled game time (affected by Time.timeScale)+yield return new WaitForSecondsRealtime(2f);// wait 2s of real time (ignores timeScale; good for pause menus)+yield return new WaitForFixedUpdate(); // resume after the next physics step+yield return new WaitUntil(() => isReady); // resume once the predicate is true+yield return new WaitWhile(() => isLoading);// resume once the predicate is false+yield return StartCoroutine(OtherRoutine());// run a nested coroutine to completion first+```++## Stopping coroutines deterministically++Keep the handle so you can stop exactly the right routine:++```csharp+private Coroutine _spawnLoop;++private void OnEnable() => _spawnLoop = StartCoroutine(SpawnLoop());+private void OnDisable() { if (_spawnLoop != null) StopCoroutine(_spawnLoop); }++private System.Collections.IEnumerator SpawnLoop()+{+ var wait = new WaitForSeconds(1f); // allocate once, reuse — avoids per-iteration GC+ while (true)+ {+ Spawn();+ yield return wait;+ }+}+```++`StopAllCoroutines()` stops every coroutine on the MonoBehaviour — convenient but blunt;+prefer stopping by handle when multiple routines run on one object.++## Custom yield instruction++When you want a reusable wait condition:++```csharp+public class WaitForAnimationEnd : CustomYieldInstruction+{+ private readonly Animator _a;+ private readonly int _layer;+ public WaitForAnimationEnd(Animator a, int layer = 0) { _a = a; _layer = layer; }+ // keepWaiting == true means "keep yielding"; false resumes the coroutine.+ public override bool keepWaiting => _a.GetCurrentAnimatorStateInfo(_layer).normalizedTime < 1f;+}+```++## Gotchas++- Coroutines are killed when the GameObject is **deactivated** (`SetActive(false)`) or the+ script is destroyed — but *not* when only the script component is disabled while the object+ stays active. Re-arm in `OnEnable` if needed.+- A coroutine started from `Awake` will not advance past its first `yield` until the object is+ active and the script enabled. Prefer starting loops in `OnEnable`/`Start`.+- Allocating `new WaitForSeconds(x)` every loop iteration creates garbage; cache the instance.diff --git a/skills/unity/unity-input-system/SKILL.md b/skills/unity/unity-input-system/SKILL.mdnew file mode 100644index 0000000..969e7df--- /dev/null+++ b/skills/unity/unity-input-system/SKILL.md@@ -0,0 +1,145 @@+---+name: unity-input-system+description: >+ Wire player input in Unity 6 with the Input System package: Input Actions, action maps,+ the PlayerInput component, and reading values via callbacks or polling. Use when the+ project has a .inputactions asset or com.unity.inputsystem, or when the user mentions the+ Unity Input System, InputAction, action maps, PlayerInput, control schemes, or rebinding.+license: Apache-2.0+compatibility: Unity 6 (6000.0 LTS); Input System package 1.x (com.unity.inputsystem)+metadata:+ engine: unity+ category: unity+ difficulty: intermediate+---++# Unity Input System (new)++Read input through Unity's **Input System package** (`com.unity.inputsystem`, 1.x) —+action-based, device-agnostic, rebindable. Targets **Unity 6**. This is the modern+replacement for the legacy `Input.GetAxis`/`Input.GetKey` Input Manager.++## When to use++- Use when setting up movement/jump/fire input, defining an `.inputactions` asset with+ action maps and control schemes, wiring a `PlayerInput` component, reading a `Vector2`+ stick/WASD value, or handling gamepad + keyboard + touch from one set of actions.+- Use when `Packages/manifest.json` contains `com.unity.inputsystem` or the project has an+ `*.inputactions` asset.++**When *not* to use:** rebindable-control *architecture* across engines → `input-systems`+(this skill is the Unity-specific API). Moving the character once you have the input vector+→ `unity-physics` / `unity-csharp-scripting`.++## Core workflow++1. **Check Active Input Handling** (Project Settings → Player). The package only receives+ input when this is `Input System Package (New)` or `Both`. `Both` is required if any old+ `Input.GetAxis` code remains.+2. **Create an `.inputactions` asset.** Add an *action map* (e.g. `Gameplay`), add *actions*+ (`Move` = Value/Vector2, `Jump` = Button, `Fire` = Button), and bind them to controls and+ composite bindings (WASD = 2D Vector composite).+3. **Choose how to read it:**+ - **`PlayerInput` component** (designer-friendly) — drop it on the player, point it at the+ asset, pick a *Behavior* (Send Messages / Broadcast / Invoke Unity Events / Invoke C#+ Events). Best for single/local-coop players.+ - **Direct in code** (`InputActionReference` / `InputActionAsset`) — most control; you+ `Enable()` actions and read them. Best for systems and tools.+4. **Enable the actions/maps you read.** `PlayerInput` enables its default map automatically;+ actions you reference yourself must be `.Enable()`d (and disabled on teardown).+5. **Switch action maps** for context (gameplay ↔ UI/menu) instead of guarding every handler.+6. **Verify** with the Input Debugger (Window → Analysis → Input Debugger) to confirm devices+ and that actions fire.++## Patterns++### 1. `PlayerInput` with "Send Messages" (handlers on the same GameObject)++```csharp+using UnityEngine;+using UnityEngine.InputSystem;++// PlayerInput (Behavior = Send Messages) calls On<ActionName>(InputValue) by name.+public class PlayerInputReceiver : MonoBehaviour+{+ private Vector2 _move;++ private void OnMove(InputValue value) => _move = value.Get<Vector2>(); // Move action+ private void OnJump(InputValue value) { if (value.isPressed) Jump(); } // Button action++ private void Update() { /* drive movement from _move */ }+ private void Jump() { }+}+```++### 2. Reading an action directly in code (polling a value)++```csharp+using UnityEngine;+using UnityEngine.InputSystem;++public class DirectMover : MonoBehaviour+{+ [SerializeField] private InputActionReference moveAction; // assign the Move action++ private void OnEnable() => moveAction.action.Enable(); // REQUIRED or it reads zero+ private void OnDisable() => moveAction.action.Disable();++ private void Update()+ {+ Vector2 move = moveAction.action.ReadValue<Vector2>(); // continuous value+ transform.Translate(new Vector3(move.x, 0, move.y) * (5f * Time.deltaTime));+ }+}+```++### 3. Event callbacks + switching action maps (gameplay ↔ UI)++```csharp+[SerializeField] private InputActionAsset actions;++private void OnEnable()+{+ actions.FindAction("Gameplay/Fire").performed += OnFire; // edge event: fires once+ actions.FindActionMap("Gameplay").Enable();+}+private void OnDisable() => actions.FindAction("Gameplay/Fire").performed -= OnFire;++private void OnFire(InputAction.CallbackContext ctx) => Shoot(); // ctx.ReadValue<T>() if needed++private void OpenPauseMenu() // change context, don't sprinkle if-checks+{+ actions.FindActionMap("Gameplay").Disable();+ actions.FindActionMap("UI").Enable();+}+private void Shoot() { }+```++## Pitfalls++- **No input at all** → either Active Input Handling is still `Input Manager (Old)`, or you+ forgot to `Enable()` the action/map. `PlayerInput` auto-enables; raw `InputAction`s do not.+- **`InvalidOperationException` about the old input backend** → some script still calls+ `Input.GetAxis`/`Input.GetKey` while Active Input Handling is `New`. Port it or set `Both`.+- **Buttons read as 0 with `ReadValue`** → button *presses* are edge events; use the+ `performed` callback (or `WasPressedThisFrame()`), not per-frame `ReadValue` for triggers.+- **`Send Messages` handlers never fire** → the receiving script must be on the *same*+ GameObject as the `PlayerInput`; `Broadcast Messages` reaches children too.+- **Leaking subscriptions** → unsubscribe (`-=`) in `OnDisable`; re-subscribing in `OnEnable`+ without unsubscribing doubles up handlers.+- **Touch/gamepad not detected** → enable the matching control scheme and confirm the device+ in the Input Debugger; the Vector2 composite needs all four bindings set.++## References++- For interactive control **rebinding** (`PerformInteractiveRebinding`), saving/loading+ bindings as JSON, and **local multiplayer** with `PlayerInputManager`, read+ `references/rebinding.md`.+- Primary docs: Unity Manual "Input System"+ (`https://docs.unity3d.com/Manual/com.unity.inputsystem.html`).++## Related skills++- `input-systems` — engine-agnostic input architecture (rebinding, buffering, multi-device).+- `unity-csharp-scripting` — the MonoBehaviour these handlers live in.+- `unity-physics` — applying the input vector to a Rigidbody.diff --git a/skills/unity/unity-input-system/references/rebinding.md b/skills/unity/unity-input-system/references/rebinding.mdnew file mode 100644index 0000000..e11c0b3--- /dev/null+++ b/skills/unity/unity-input-system/references/rebinding.md@@ -0,0 +1,91 @@+# Interactive rebinding & local multiplayer (Input System 1.x)++Depth for `unity-input-system`: runtime control rebinding and split-screen local co-op.+APIs are from `com.unity.inputsystem` 1.x (`UnityEngine.InputSystem`).++## Interactive rebinding ("press a key to rebind")++`InputActionRebindingExtensions.PerformInteractiveRebinding` listens for the next control the+player actuates and rewrites that binding as an override.++```csharp+using UnityEngine.InputSystem;++private InputActionRebindingExtensions.RebindingOperation _rebind;++public void StartRebind(InputAction action, int bindingIndex)+{+ action.Disable(); // must be disabled while rebinding+ _rebind = action.PerformInteractiveRebinding(bindingIndex)+ .WithControlsExcluding("<Mouse>/position") // ignore noisy controls+ .OnMatchWaitForAnother(0.1f)+ .OnComplete(op =>+ {+ op.Dispose(); // always dispose the operation+ action.Enable();+ SaveBindings(action.actionMap.asset); // persist (see below)+ })+ .Start();+}+```++- Rebinds are stored as **binding overrides** on top of the asset's defaults; the asset is not+ modified on disk.+- Reset a single binding with `action.RemoveBindingOverride(bindingIndex)` or all with+ `action.actionMap.RemoveAllBindingOverrides()`.+- Show the current binding text with+ `action.GetBindingDisplayString(bindingIndex)`.++## Saving & loading rebinds++Serialize only the overrides as JSON and restore them on load:++```csharp+private const string Key = "input_rebinds";++void SaveBindings(InputActionAsset asset)+ => PlayerPrefs.SetString(Key, asset.SaveBindingOverridesAsJson());++void LoadBindings(InputActionAsset asset)+{+ if (PlayerPrefs.HasKey(Key))+ asset.LoadBindingOverridesFromJson(PlayerPrefs.GetString(Key));+}+```++`PlayerPrefs` is fine for keybinds; for larger save data use the `save-systems` approach.++## Local multiplayer with `PlayerInputManager`++For split-screen / shared-screen co-op, add a `PlayerInputManager` component and a player+prefab that has a `PlayerInput`. The manager spawns one player per joining device.++```csharp+using UnityEngine.InputSystem;++public class CoopSpawner : MonoBehaviour+{+ private void OnEnable() => PlayerInputManager.instance.onPlayerJoined += HandleJoin;+ private void OnDisable() => PlayerInputManager.instance.onPlayerJoined -= HandleJoin;++ private void HandleJoin(PlayerInput player)+ {+ // Each PlayerInput owns its paired device(s); player.playerIndex identifies them.+ Debug.Log($"Player {player.playerIndex} joined on {player.devices[0].displayName}");+ }+}+```++- **Join Behavior** controls how players join (Join Players When Button Is Pressed, on action,+ or manually via `JoinPlayer`).+- Each `PlayerInput` is auto-assigned its own device(s), so two gamepads drive two players+ without extra wiring.+- Per-player UI needs a `MultiplayerEventSystem` + `InputSystemUIInputModule` per player.++## Gotchas++- Always `Dispose()` the `RebindingOperation` in `OnComplete`/`OnCancel`, or it leaks and+ keeps listening.+- Disable the action before rebinding it; rebinding an enabled action throws.+- Composite bindings (e.g. WASD) have multiple binding indices — rebind each part separately+ by its index, not the composite root.diff --git a/skills/unity/unity-navmesh/SKILL.md b/skills/unity/unity-navmesh/SKILL.mdnew file mode 100644index 0000000..c50d3f3--- /dev/null+++ b/skills/unity/unity-navmesh/SKILL.md@@ -0,0 +1,136 @@+---+name: unity-navmesh+description: >+ Add AI navigation in Unity 6: bake a NavMesh with the AI Navigation package (NavMeshSurface),+ move agents with NavMeshAgent.SetDestination, and handle dynamic obstacles. Use when setting+ up pathfinding, making an enemy chase the player, baking navigation, or when the user+ mentions NavMesh, NavMeshAgent, NavMeshSurface, NavMeshObstacle, or Unity pathfinding.+license: Apache-2.0+compatibility: Unity 6 (6000.0 LTS); AI Navigation package 2.x (com.unity.ai.navigation); UnityEngine.AI runtime.+metadata:+ engine: unity+ category: unity+ difficulty: intermediate+---++# Unity NavMesh (AI Navigation)++Give NPCs pathfinding in Unity 6: bake walkable surfaces and move agents around obstacles.+Targets **Unity 6 (6000.0 LTS)** with the **AI Navigation package 2.x**.++> **Version trap (Unity 2022+/6):** the old built-in **Navigation window** (Object/Bake tabs)+> is gone. Baking is now **component-based** via the **AI Navigation package**+> (`com.unity.ai.navigation`): add a **NavMeshSurface** to your level geometry and click+> **Bake**. The *runtime* `NavMeshAgent`/`NavMesh` API stays in built-in `UnityEngine.AI`.++## When to use++- Use when an agent needs to walk/chase/patrol to a target, when baking a navigable surface,+ adding dynamic blockers (`NavMeshObstacle`), or checking whether a destination is reachable.+- Use when the project has the AI Navigation package, a `NavMeshSurface` component, or scripts+ using `UnityEngine.AI.NavMeshAgent`.++**When *not* to use:** the *decision* logic of when/where to move (FSMs, behaviour trees,+steering) → `game-ai` (this skill is the Unity movement/pathing mechanism). Force-driven or+kinematic movement that isn't pathfinding → `unity-physics`.++## Core workflow++1. **Install the AI Navigation package** (Package Manager → `com.unity.ai.navigation`).+2. **Bake a surface:** select the static level geometry, **Add Component → Navigation → NavMesh+ Surface**, set the agent type/area settings, and click **Bake**. Re-bake whenever geometry,+ `NavMeshModifier`s, or agent settings change.+3. **Add a `NavMeshAgent`** to each moving NPC; its radius/height/speed must match the baked+ agent type, and it must spawn *on* the baked mesh.+4. **Drive it from script** with `SetDestination(targetPos)`; the agent steers and avoids other+ agents automatically. Detect arrival with `remainingDistance`/`pathPending`.+5. **Handle dynamic blockers** with `NavMeshObstacle` (carving) so closed doors/crates block+ paths without a full re-bake.+6. **Verify** with the AI Navigation overlay (the baked mesh is drawn in the Scene view) and by+ watching agents path around obstacles to the goal; check `NavMeshPath.status` for+ unreachable targets.++## Patterns++### 1. Chase/seek with a NavMeshAgent++```csharp+using UnityEngine;+using UnityEngine.AI;++[RequireComponent(typeof(NavMeshAgent))]+public class Chaser : MonoBehaviour+{+ [SerializeField] private Transform target;+ private NavMeshAgent _agent;++ private void Awake() => _agent = GetComponent<NavMeshAgent>();++ private void Update()+ {+ if (target) _agent.SetDestination(target.position); // re-path toward the target+ }++ // Arrived? pathPending guards the first frame before a path exists.+ private bool HasArrived() =>+ !_agent.pathPending && _agent.remainingDistance <= _agent.stoppingDistance;+}+```++### 2. Check reachability before committing++```csharp+using UnityEngine.AI;++public bool CanReach(NavMeshAgent agent, Vector3 destination)+{+ var path = new NavMeshPath();+ agent.CalculatePath(destination, path);+ return path.status == NavMeshPathStatus.PathComplete; // vs Partial / Invalid+}+```++### 3. Bake at runtime (for procedurally built or streamed levels)++```csharp+using Unity.AI.Navigation; // the package namespace (NavMeshSurface)++[SerializeField] private NavMeshSurface surface;++// After spawning level geometry, build the navmesh in code.+public void RebuildNav() => surface.BuildNavMesh();+```++### 4. Dynamic obstacle that carves the mesh++```csharp+// Add a NavMeshObstacle (Carve = true) to a door/crate. While present it cuts a hole in the+// navmesh so agents route around it; remove/disable it to reopen the path — no re-bake needed.+```++## Pitfalls++- **Looking for the Navigation window** — it no longer exists in Unity 6. Use the AI Navigation+ package's `NavMeshSurface` component + Bake.+- **Agent doesn't move / warps to origin** — it isn't on the baked mesh, or no surface was+ baked. Bake the surface and spawn the agent on it (`NavMesh.SamplePosition` to snap).+- **Agent ignores new geometry** — the navmesh is baked; runtime-spawned obstacles need a+ `NavMeshObstacle` (carving) or a `surface.BuildNavMesh()` re-bake.+- **`SetDestination` every frame is wasteful** — for a slow-moving target, re-path on a timer+ (e.g. every 0.2s) instead of each frame.+- **Agent radius/height mismatch** — if the `NavMeshAgent`'s size differs from the baked agent+ type, it gets stuck in gaps or floats; keep them consistent.+- **Agents jitter against each other** — tune `avoidancePriority` and quality, or use an+ obstacle for truly static blockers rather than relying on agent avoidance.++## References++- Primary docs: AI Navigation package manual+ (`https://docs.unity3d.com/Packages/[email protected]/manual/index.html`) and+ `ScriptReference/AI.NavMeshAgent`, `ScriptReference/AI.NavMesh`.++## Related skills++- `game-ai` — engine-agnostic decision-making (FSM, behaviour trees, steering) that *uses* this.+- `unity-csharp-scripting` — the MonoBehaviour structure around the agent.+- `tower-defense` / `fps-shooter` — genres that compose pathfinding with gameplay.diff --git a/skills/unity/unity-physics/SKILL.md b/skills/unity/unity-physics/SKILL.mdnew file mode 100644index 0000000..f1ca8e2--- /dev/null+++ b/skills/unity/unity-physics/SKILL.md@@ -0,0 +1,151 @@+---+name: unity-physics+description: >+ Set up 3D physics in Unity 6: Rigidbody movement and forces, colliders, triggers vs+ collisions, layer-based collision, raycasts, and joints. Use when adding a Rigidbody,+ handling OnCollisionEnter/OnTriggerEnter, tuning collision layers, casting rays, or when+ the user mentions Unity physics, AddForce, isKinematic, or linearVelocity.+license: Apache-2.0+compatibility: Unity 6 (6000.0 LTS), built-in PhysX. Note the velocity → linearVelocity rename.+metadata:+ engine: unity+ category: unity+ difficulty: intermediate+---++# Unity Physics (Rigidbody / PhysX)++Make objects move, collide, and detect each other with Unity 6's built-in 3D physics+(PhysX). Get the `FixedUpdate` discipline, trigger-vs-collision rules, and collision layers+right. Targets **Unity 6 (6000.0 LTS)**.++> **Unity 6 rename:** `Rigidbody.velocity` is now **`Rigidbody.linearVelocity`** (the old+> name is deprecated). Code copied from older tutorials will warn or fail to compile.++## When to use++- Use when giving an object physical motion (forces, velocity, gravity), responding to+ collisions or triggers, setting up collision layers/masks, raycasting for ground checks or+ line-of-sight, or connecting bodies with joints.+- Use when scenes/prefabs contain `Rigidbody` + `Collider` components.++**When *not* to use:** 2D physics (`Rigidbody2D`, `Collider2D`) is a separate API — adapt the+concepts but the types differ. Cross-engine *feel* tuning (timestep, jitter, tunnelling) →+`physics-tuning`. Reading input that drives movement → `unity-input-system`.++## Core workflow++1. **Add a `Rigidbody`** to anything that should be simulated; add a `Collider` to anything+ that should be hit. A collision needs a `Collider` on both, and at least one `Rigidbody`.+2. **Do all physics in `FixedUpdate`.** Read input in `Update`, store intent, then apply+ forces / set `linearVelocity` / call `MovePosition` in `FixedUpdate`.+3. **Move bodies through the physics API, not the Transform.** Use `AddForce`,+ `linearVelocity`, or `MovePosition` — never assign `transform.position` to a non-kinematic+ Rigidbody (it teleports and breaks collision resolution).+4. **Pick collision vs trigger.** A solid collision blocks and calls `OnCollisionEnter`; a+ `Collider` with `Is Trigger` checked passes through and calls `OnTriggerEnter`.+5. **Organise interactions with layers.** Put objects on layers and edit the Layer Collision+ Matrix (Project Settings → Physics) so unrelated things don't test against each other.+6. **Verify** with the Physics Debugger (Window → Analysis → Physics Debugger) and by watching+ for jitter; if fast objects pass through walls, raise Collision Detection mode.++## Patterns++### 1. Force-based movement in `FixedUpdate` (with a speed clamp)++```csharp+using UnityEngine;++[RequireComponent(typeof(Rigidbody))]+public class Mover : MonoBehaviour+{+ [SerializeField] private float accel = 30f, maxSpeed = 8f;+ private Rigidbody _rb;+ private Vector3 _input; // set from Update / input system++ private void Awake() => _rb = GetComponent<Rigidbody>();++ private void FixedUpdate()+ {+ _rb.AddForce(_input * accel, ForceMode.Acceleration); // mass-independent accel+ // Unity 6: linearVelocity (was 'velocity'). Clamp horizontal speed.+ Vector3 flat = new(_rb.linearVelocity.x, 0, _rb.linearVelocity.z);+ if (flat.magnitude > maxSpeed)+ {+ flat = flat.normalized * maxSpeed;+ _rb.linearVelocity = new Vector3(flat.x, _rb.linearVelocity.y, flat.z);+ }+ }+}+```++`ForceMode`: `Force` (continuous, mass-scaled), `Acceleration` (continuous, ignores mass),+`Impulse` (instant, mass-scaled — jumps), `VelocityChange` (instant, ignores mass).++### 2. Collision vs trigger callbacks++```csharp+// Solid hit: both have colliders, this one has a (non-kinematic) Rigidbody.+private void OnCollisionEnter(Collision col)+{+ Debug.Log($"Hit {col.gameObject.name} at {col.contacts[0].point}");+}++// Overlap: one collider has 'Is Trigger' = true. Requires a Rigidbody on at least one party.+private void OnTriggerEnter(Collider other)+{+ if (other.CompareTag("Pickup")) Destroy(other.gameObject);+}+```++### 3. Ground check with a layer-masked raycast++```csharp+[SerializeField] private LayerMask groundMask; // set to your "Ground" layer in the Inspector++private bool IsGrounded()+{+ // Cast a short ray down; only test colliders on groundMask.+ return Physics.Raycast(transform.position, Vector3.down, out RaycastHit hit,+ 1.1f, groundMask);+}+```++### 4. Kinematic platform that still pushes bodies++```csharp+// isKinematic Rigidbody: not driven by forces, but MovePosition interpolates and carries+// resting bodies correctly (unlike moving the Transform directly).+private void FixedUpdate() => _rb.MovePosition(_rb.position + Vector3.right * (2f * Time.fixedDeltaTime));+```++## Pitfalls++- **`Rigidbody.velocity` doesn't exist in Unity 6** — use `linearVelocity` (and+ `angularVelocity` is unchanged).+- **Setting `transform.position` on a dynamic Rigidbody** — teleports it, skips collision.+ Use `MovePosition` (kinematic/interpolated) or apply forces.+- **Applying forces in `Update`** — frame-rate-dependent and jittery. Physics goes in+ `FixedUpdate`.+- **Trigger callbacks never fire** — triggers need a `Rigidbody` on at least one of the two+ colliders, and both colliders enabled; two static triggers don't report overlaps.+- **Fast objects pass through walls (tunnelling)** — set the Rigidbody's Collision Detection+ to `Continuous` (or `Continuous Dynamic`) for bullets/fast movers.+- **Non-uniform-scaled `MeshCollider`s or scaled colliders** misbehave; prefer primitive+ colliders and keep scale uniform.+- **Everything collides with everything** — wasted cost; assign layers and prune the Layer+ Collision Matrix.++## References++- For raycast variants (`SphereCast`, `RaycastAll`, `OverlapSphere`, `LayerMask` bit math) and+ joints (`FixedJoint`, `HingeJoint`, `ConfigurableJoint`, breakable joints), read+ `references/raycasting-and-joints.md`.+- Primary docs: Unity Manual "Physics" section and `ScriptReference/Rigidbody`,+ `ScriptReference/Physics.Raycast`.++## Related skills++- `physics-tuning` — engine-agnostic feel: fixed timestep, mass/drag, CCD, stability.+- `unity-csharp-scripting` — the `FixedUpdate`/`Update` split these patterns rely on.+- `unity-navmesh` — agent movement that is *not* force-driven.diff --git a/skills/unity/unity-physics/references/raycasting-and-joints.md b/skills/unity/unity-physics/references/raycasting-and-joints.mdnew file mode 100644index 0000000..2b8a143--- /dev/null+++ b/skills/unity/unity-physics/references/raycasting-and-joints.md@@ -0,0 +1,81 @@+# Raycasting variants & joints (Unity 6 PhysX)++Depth for `unity-physics`. All types are in `UnityEngine`. Verified against+`ScriptReference/Physics` and the joint component pages.++## LayerMask bit math++A `LayerMask` is a 32-bit set of layers. Common constructions:++```csharp+int mask = LayerMask.GetMask("Ground", "Enemy"); // by name (recommended)+int onlyGround = 1 << LayerMask.NameToLayer("Ground"); // single layer by index+int everythingButPlayer = ~(1 << LayerMask.NameToLayer("Player")); // invert+```++`Physics.Raycast(..., layerMask)` tests only layers whose bit is set. To *ignore* triggers+in a cast, pass `QueryTriggerInteraction.Ignore` as the last argument.++## Cast variants++```csharp+// Single nearest hit along a ray.+if (Physics.Raycast(origin, dir, out RaycastHit hit, maxDistance, mask)) { /* hit.point, hit.normal, hit.collider */ }++// Thick ray — good for "can a character-sized body pass?".+if (Physics.SphereCast(origin, radius, dir, out RaycastHit sHit, maxDistance, mask)) { }++// All hits along the ray (unordered) — e.g. shoot-through targets.+RaycastHit[] hits = Physics.RaycastAll(origin, dir, maxDistance, mask);++// Non-allocating versions write into a buffer you own (no GC each call) — prefer in hot paths.+private readonly RaycastHit[] _buffer = new RaycastHit[8];+int count = Physics.RaycastNonAlloc(origin, dir, _buffer, maxDistance, mask);++// Overlap tests (no direction): what is inside this volume right now?+Collider[] inRange = Physics.OverlapSphere(center, radius, mask);+```++Tips:+- `RaycastHit.normal` is the surface normal at the hit — use it to align decals or compute+ slope angle (`Vector3.Angle(hit.normal, Vector3.up)`).+- Prefer the `NonAlloc` / buffer overloads in per-frame code to avoid garbage.+- A ray starting *inside* a collider does not report that collider unless+ `Physics.queriesHitBackfaces` / start outside it.++## Joints++Joints connect two Rigidbodies (or a body to the world if `Connected Body` is empty).++| Joint | Constrains | Typical use |+|-------|-----------|-------------|+| `FixedJoint` | all 6 DOF (rigidly attaches) | weld parts that can break apart |+| `HingeJoint` | rotation about one axis, with motor/limits/spring | doors, wheels, pendulums |+| `SpringJoint` | distance via a spring | bungee, soft tethers |+| `ConfigurableJoint` | any combination of the 6 DOF | custom ragdoll/vehicle constraints |++```csharp+// A motorised hinge (e.g. a powered door).+var hinge = gameObject.AddComponent<HingeJoint>();+hinge.axis = Vector3.up;+hinge.useMotor = true;+hinge.motor = new JointMotor { force = 100f, targetVelocity = 90f /* deg/s */ };+```++### Breakable joints++```csharp+fixedJoint.breakForce = 500f; // newtons before the joint snaps+fixedJoint.breakTorque = 500f;+// When it breaks, the engine calls this on the GameObject:+private void OnJointBreak(float breakForce) => Debug.Log($"Joint broke at {breakForce}");+```++## Gotchas++- Joints simulate in `FixedUpdate`; setting joint properties is fine from `Update` but effects+ apply on the next physics step.+- A `ConfigurableJoint`'s locked/limited axes are relative to the joint's initial orientation —+ set up the bodies in their rest pose before adding the joint.+- Very stiff joints + high mass ratios are unstable; increase `Default Solver Iterations`+ (Project Settings → Physics) before fighting it with bigger forces.diff --git a/skills/unity/unity-scriptableobjects/SKILL.md b/skills/unity/unity-scriptableobjects/SKILL.mdnew file mode 100644index 0000000..3e16124--- /dev/null+++ b/skills/unity/unity-scriptableobjects/SKILL.md@@ -0,0 +1,125 @@+---+name: unity-scriptableobjects+description: >+ Architect Unity 6 data and decoupling with ScriptableObjects: config/data assets, shared+ runtime variables, event channels, and runtime sets/registries. Use when designing+ data-driven systems, replacing singletons/managers, creating .asset data with+ CreateAssetMenu, or when the user mentions ScriptableObject, SO architecture, or data assets.+license: Apache-2.0+compatibility: Unity 6 (6000.0 LTS); UnityEngine.ScriptableObject+metadata:+ engine: unity+ category: unity+ difficulty: intermediate+---++# Unity ScriptableObject Architecture++Use `ScriptableObject` assets to store shared data and decouple systems in Unity 6 —+configuration, event channels, and registries that live as project assets instead of being+hard-wired into scenes or singletons. Targets **Unity 6 (6000.0 LTS)**.++## When to use++- Use when you need designer-editable config (weapon stats, level data), to share one value+ between unrelated systems, to decouple senders from listeners via event channels, or to+ build a runtime registry of active objects — without a `static`/singleton manager.+- Use when the project has `*.asset` data files backed by `: ScriptableObject` classes.++**When *not* to use:** per-instance runtime state that differs per GameObject (that belongs on+a MonoBehaviour) — a ScriptableObject asset is *shared* by everyone who references it. Saving+player progress to disk → `save-systems`. Plain DTOs that never need to be an asset can just be+`[System.Serializable]` classes.++## Core workflow++1. **Define the class** deriving from `ScriptableObject` and tag it with `[CreateAssetMenu]` so+ designers can create instances from the Assets menu.+2. **Create one or more `.asset` instances** in the Project window; each is a shared, named+ piece of data referenced by `[SerializeField]` fields.+3. **Reference, don't copy.** MonoBehaviours hold a reference to the asset; they all see the+ same data, so changing the asset changes every consumer.+4. **For decoupling**, model *signals* and *shared variables* as ScriptableObjects: a+ "FloatVariable" the HUD reads and the player writes; an "event channel" the player raises+ and many systems listen to. Neither side references the other.+5. **Reset runtime mutations** in `OnEnable` if the asset is mutated during play, because edits+ made in the Editor at runtime persist on the asset (a frequent source of "my values+ changed after I played").+6. **Verify** by inspecting the asset values during Play mode and confirming consumers react.++## Patterns++### 1. Config/data asset++```csharp+using UnityEngine;++[CreateAssetMenu(fileName = "WeaponData", menuName = "Game/Weapon Data", order = 0)]+public class WeaponData : ScriptableObject+{+ public string displayName = "Pistol";+ public int damage = 10;+ public float fireRate = 0.25f;+ public GameObject projectilePrefab;+}+```++```csharp+public class Weapon : MonoBehaviour+{+ [SerializeField] private WeaponData data; // assign the shared asset in the Inspector+ private void Fire() => Debug.Log($"{data.displayName} for {data.damage}");+}+```++### 2. Shared runtime variable (decouples producer from consumer)++```csharp+[CreateAssetMenu(menuName = "Game/Float Variable")]+public class FloatVariable : ScriptableObject+{+ [SerializeField] private float initialValue;+ [System.NonSerialized] public float runtimeValue; // not saved to the asset++ private void OnEnable() => runtimeValue = initialValue; // reset each play session+}+// Player writes playerHealth.runtimeValue; the HUD reads it — neither references the other.+```++### 3. Creating an instance at runtime (not an asset on disk)++```csharp+// For transient SO data you build in code (e.g. a generated config).+var temp = ScriptableObject.CreateInstance<WeaponData>();+temp.damage = 25;+// ...use temp... Destroy(temp); // clean up runtime-created instances+```++## Pitfalls++- **Editing an SO at runtime persists in the Editor** — values you change during Play stay+ changed on the asset after you stop. Keep mutable runtime state in `[NonSerialized]` fields+ reset in `OnEnable`, or it will surprise you. (In a *build*, asset edits do not persist+ across launches.)+- **Expecting per-object state** — every reference points to the *same* asset. If two enemies+ need different current HP, store HP on the MonoBehaviour, not the shared SO.+- **No frame lifecycle** — ScriptableObjects have `OnEnable`/`OnDisable`/`OnDestroy` but no+ `Update`. Don't expect per-frame callbacks.+- **Using SOs as a save file** — they're authoring assets, not runtime persistence; write+ progress with `save-systems` instead.+- **Leaking `CreateInstance` objects** — runtime-created instances are not garbage-collected+ like plain C# objects; `Destroy` them when done.++## References++- For the **event-channel** pattern (a `GameEvent` SO + listeners, type-safe payloads) and+ **runtime sets/registries** (a shared list of active enemies), read+ `references/event-channels.md`.+- Primary docs: Unity Manual "ScriptableObject" (`/Manual/class-ScriptableObject.html`) and+ `ScriptReference/ScriptableObject`, `ScriptReference/CreateAssetMenuAttribute`.++## Related skills++- `unity-csharp-scripting` — the MonoBehaviours that consume these assets.+- `save-systems` — persisting state to disk (what SOs are *not* for).+- `card-game` / `rpg` / `survival-crafting` — genres that lean on SO-driven data.diff --git a/skills/unity/unity-scriptableobjects/references/event-channels.md b/skills/unity/unity-scriptableobjects/references/event-channels.mdnew file mode 100644index 0000000..1a9be9b--- /dev/null+++ b/skills/unity/unity-scriptableobjects/references/event-channels.md@@ -0,0 +1,104 @@+# Event channels & runtime sets (Unity 6 ScriptableObjects)++Depth for `unity-scriptableobjects`: two decoupling patterns that are the main reason teams+adopt SO architecture. Verified against the Unity Manual ScriptableObject docs; the design is+original.++## Event channel (publisher/subscriber with no direct references)++A raiser (e.g. the player dying) and listeners (UI, audio, spawner) both reference a shared+`GameEvent` asset, never each other. Add/remove the asset to wire systems together in the+Inspector.++```csharp+using System.Collections.Generic;+using UnityEngine;++[CreateAssetMenu(menuName = "Game/Events/Game Event")]+public class GameEvent : ScriptableObject+{+ private readonly List<GameEventListener> _listeners = new();++ public void Raise()+ {+ // iterate backwards so a listener that unregisters in its handler is safe+ for (int i = _listeners.Count - 1; i >= 0; i--)+ _listeners[i].OnRaised();+ }++ public void Register(GameEventListener l) { if (!_listeners.Contains(l)) _listeners.Add(l); }+ public void Unregister(GameEventListener l) { _listeners.Remove(l); }+}+```++```csharp+using UnityEngine;+using UnityEngine.Events;++public class GameEventListener : MonoBehaviour+{+ [SerializeField] private GameEvent channel;+ [SerializeField] private UnityEvent response; // wire reactions in the Inspector++ private void OnEnable() => channel.Register(this);+ private void OnDisable() => channel.Unregister(this); // always unregister+ public void OnRaised() => response.Invoke();+}+```++Usage: the player calls `onPlayerDied.Raise()`; the HUD, the music manager, and the respawner+each have a `GameEventListener` pointing at `onPlayerDied` with their own response. Adding a+new reaction is an Inspector change, not a code change.++### Typed payloads++For events that carry data, make a generic base or a concrete typed channel:++```csharp+[CreateAssetMenu(menuName = "Game/Events/Int Event")]+public class IntEvent : ScriptableObject+{+ public event System.Action<int> OnRaised;+ public void Raise(int value) => OnRaised?.Invoke(value); // e.g. score delta+}+```++Prefer a small number of concrete typed channels (`IntEvent`, `Vector3Event`) over a fully+generic `GameEvent<T>` because Unity cannot create assets for open generic types directly.++## Runtime set / registry (a shared, live collection)++Instead of `FindObjectsOfType` every frame, objects add themselves to a shared set on enable+and remove on disable. Systems (AI targeting, minimap) read the set.++```csharp+[CreateAssetMenu(menuName = "Game/Runtime Set/Enemy Set")]+public class EnemyRuntimeSet : ScriptableObject+{+ public readonly List<Enemy> Items = new();+ public void Add(Enemy e) { if (!Items.Contains(e)) Items.Add(e); }+ public void Remove(Enemy e) => Items.Remove(e);+}+```++```csharp+public class Enemy : MonoBehaviour+{+ [SerializeField] private EnemyRuntimeSet set;+ private void OnEnable() => set.Add(this);+ private void OnDisable() => set.Remove(this); // keep the set clean+}+```++Now "nearest enemy" is a loop over `set.Items` — no scene scans, and the list reflects exactly+what is alive.++## Gotchas++- `List` fields on a ScriptableObject are populated at runtime and **persist in the Editor**+ between play sessions unless cleared. Clear runtime sets in `OnEnable` (or `OnDisable`) so a+ stale entry from the last session doesn't linger.+- Always `Unregister`/`Remove` in `OnDisable`; objects destroyed without cleanup leave null+ entries that crash listeners.+- Event channels invoke synchronously on the raiser's thread/frame — a heavy listener stalls+ the raiser. Keep handlers light or marshal heavy work to a coroutine.diff --git a/skills/unity/unity-tilemap-2d/SKILL.md b/skills/unity/unity-tilemap-2d/SKILL.mdnew file mode 100644index 0000000..c9463e8--- /dev/null+++ b/skills/unity/unity-tilemap-2d/SKILL.md@@ -0,0 +1,125 @@+---+name: unity-tilemap-2d+description: >+ Build and script 2D tilemaps in Unity 6: the Grid + Tilemap components, the Tile Palette,+ tilemap colliders, rule tiles, and runtime SetTile/GetTile painting. Use when painting tile+ levels, adding a TilemapCollider2D, using rule or animated tiles, generating tilemaps from+ code, or when the user mentions Unity tilemap, tile palette, rule tile, or Grid.+license: Apache-2.0+compatibility: Unity 6 (6000.0 LTS); UnityEngine.Tilemaps. RuleTile needs the 2D Tilemap Extras package.+metadata:+ engine: unity+ category: unity+ difficulty: intermediate+---++# Unity 2D Tilemap++Author and script tile-based 2D levels in Unity 6 with the `Grid`/`Tilemap` system, the Tile+Palette, colliders, and runtime painting. Targets **Unity 6 (6000.0 LTS)**.++> **Package note:** the core Tilemap (`Grid`, `Tilemap`, `Tile`, `TilemapCollider2D`) is+> built in. **Rule Tiles, Animated Tiles, and Tile Palette brushes live in the separate+> "2D Tilemap Extras" package (`com.unity.2d.tilemap.extras`)** — install it via Package+> Manager before using `RuleTile`.++## When to use++- Use when laying out a 2D level by painting tiles, setting up a `Grid` + `Tilemap`, adding+ collision to the map, using auto-tiling Rule Tiles, or generating/editing tiles from script.+- Use when scenes contain a `Grid` with `Tilemap` children, or `*.asset` tile/palette files.++**When *not* to use:** level *design* practice (pacing, blockout, layout principles) →+`level-design`. 3D tile/grid placement → `unity` 3D tooling. The platformer character that+moves over the tiles → `platformer` / `unity-physics`.++## Core workflow++1. **Create the grid:** GameObject → 2D Object → Tilemap → Rectangular. This makes a `Grid`+ with a child `Tilemap` (+ `TilemapRenderer`). Use one Tilemap per layer (background,+ ground, foreground) and set each renderer's sorting.+2. **Open the Tile Palette** (Window → 2D → Tile Palette), drag in a sliced sprite sheet to+ create `Tile` assets, then paint with the brush tools.+3. **Add collision** to the solid layer: `TilemapCollider2D`. For one merged collider (far+ cheaper and gap-free), also add `CompositeCollider2D` (+ a `Rigidbody2D` set to **Static**)+ and enable *Used By Composite* on the tilemap collider.+4. **Auto-tile with Rule Tiles** (2D Tilemap Extras) so edges/corners pick the right sprite+ automatically instead of hand-placing every variant.+5. **Edit at runtime via script** with cell coordinates (`Vector3Int`): `SetTile`, `GetTile`,+ `SetTilesBlock`, converting world↔cell with the `Grid`/`Tilemap`.+6. **Verify** in Play mode: confirm collisions (Physics Debugger), sorting order, and that+ `RefreshAllTiles` ran after bulk edits.++## Patterns++### 1. Painting tiles at runtime (cell coordinates)++```csharp+using UnityEngine;+using UnityEngine.Tilemaps;++public class TilePainter : MonoBehaviour+{+ [SerializeField] private Tilemap tilemap; // assign the target Tilemap+ [SerializeField] private TileBase groundTile;++ // World position -> cell, then place a tile.+ public void PaintAt(Vector3 worldPos)+ {+ Vector3Int cell = tilemap.WorldToCell(worldPos);+ tilemap.SetTile(cell, groundTile);+ }++ public bool IsSolid(Vector3 worldPos)+ => tilemap.GetTile(tilemap.WorldToCell(worldPos)) != null;+}+```++### 2. Bulk fill a region (faster than per-cell `SetTile`)++```csharp+// SetTilesBlock writes a whole BoundsInt in one call — use it for procedural rooms/floors.+public void FillFloor(Tilemap map, TileBase tile, int width, int height)+{+ var bounds = new BoundsInt(0, 0, 0, width, height, 1);+ var tiles = new TileBase[width * height];+ for (int i = 0; i < tiles.Length; i++) tiles[i] = tile;+ map.SetTilesBlock(bounds, tiles);+}+```++### 3. Clearing and refreshing++```csharp+tilemap.SetTile(cell, null); // null erases the tile at that cell+tilemap.RefreshAllTiles(); // re-evaluate rule/animated tiles after a bulk change+```++## Pitfalls++- **`RuleTile` type not found** — it's not built in. Install the **2D Tilemap Extras** package+ (`com.unity.2d.tilemap.extras`) via Package Manager.+- **A collider per tile tanks performance / leaves seams** — add a `CompositeCollider2D` with a+ static `Rigidbody2D` and *Used By Composite* to merge the whole layer into one smooth shape.+- **Confusing world and cell coordinates** — `SetTile`/`GetTile` take a `Vector3Int` *cell*,+ not a world position. Always convert with `WorldToCell` / `CellToWorld`.+- **Tiles render behind/in front of sprites unexpectedly** — set each `TilemapRenderer`'s+ Sorting Layer and Order in Layer; multiple tilemaps need explicit ordering.+- **Rule/animated tiles don't update after script edits** — call `RefreshAllTiles()` (or+ `RefreshTile(cell)`) after bulk `SetTilesBlock` writes.+- **Painting onto the wrong layer** — the active target Tilemap in the Tile Palette determines+ where paint lands; check the "Active Tilemap" dropdown.++## References++- Primary docs: Unity Manual "Tilemaps"+ (`https://docs.unity3d.com/Manual/tilemaps/work-with-tilemaps/tilemap-reference.html`),+ `ScriptReference/Tilemaps.Tilemap`, and the 2D Tilemap Extras package manual+ (`https://docs.unity3d.com/Packages/[email protected]/manual/index.html`) for+ Rule Tiles.++## Related skills++- `level-design` — engine-agnostic blockout, pacing, and tile layout practice.+- `procedural-gen` — generating the tile data (noise, RNG, dungeons) you feed to `SetTilesBlock`.+- `platformer` / `roguelike` — genres that compose this skill with movement and generation.