From 74000922231f270aaaa02dd3b66f20c653fdf038 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 14 Apr 2026 03:52:49 +0000 Subject: [PATCH 1/2] feat: upgrade skill from setup guide to full Unity AI development assistant Transform the skill from a passive installation manual into an active development assistant with three major improvements: 1. One-click auto-setup scripts (auto_setup.sh / auto_setup.ps1) that auto-detect and configure MCP connections for both Unity Official and Coplay paths 2. Unity operations playbook (unity_operations.md) with MCP tool reference, C# code templates, and step-by-step workflows for scene management, GameObject operations, script development, materials, asset management, debugging, and build operations 3. Rewritten SKILL.md integrating setup automation, auto-diagnosis, direct Unity operations guide, and rapid prototype workflows (3D games, 2D platformers, FPS, UI menus) https://claude.ai/code/session_01GKpTXt4npDjviK7mRzJY5A --- README.md | 97 ++++++--- SKILL.md | 410 ++++++++++++++++++++++++------------ auto_setup.ps1 | 231 +++++++++++++++++++++ auto_setup.sh | 272 ++++++++++++++++++++++++ unity_operations.md | 495 ++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 1337 insertions(+), 168 deletions(-) create mode 100644 auto_setup.ps1 create mode 100644 auto_setup.sh create mode 100644 unity_operations.md diff --git a/README.md b/README.md index f39b499..9c08eea 100644 --- a/README.md +++ b/README.md @@ -2,10 +2,11 @@ # unity-claude-code-skill -A **Claude Code Custom Skill** that guides users through setting up Claude Code -with Unity Editor via MCP (Model Context Protocol). +A **Claude Code Custom Skill** that turns Claude Code into a Unity AI +development assistant — one-click MCP setup, auto-diagnosis, and direct +Unity Editor operations via natural language. -> **What is a Claude Code Skill?** +> **What is a Claude Code Skill?** > Skills are filesystem-based instruction sets that Claude Code loads > automatically when relevant. They live in a folder with a `SKILL.md` file and > optional scripts/references. See @@ -14,24 +15,31 @@ with Unity Editor via MCP (Model Context Protocol). ## What This Skill Does -When a user asks Claude Code anything related to connecting it with Unity, this -skill provides step-by-step guidance for: +| Feature | Description | +|---------|-------------| +| **One-click setup** | Auto-setup scripts configure MCP with a single command | +| **Auto-diagnosis** | Detects and suggests fixes for connection issues | +| **Unity operations** | Templates and workflows for controlling Unity via MCP tools | +| **Rapid prototyping** | Step-by-step workflows for common game types | +| **Script generation** | C# templates for PlayerController, GameManager, UI, and more | -- **Path A – Unity Official MCP** (`com.unity.ai.assistant`) — for Unity 6+ -- **Path B – Coplay MCP** (community) — for Unity 2022+ +### MCP Paths Supported -It covers installation, configuration, connection approval, verification, and -troubleshooting for both **Windows** and **macOS**. +- **Path A — Unity Official MCP** (`com.unity.ai.assistant`) — for Unity 6+ +- **Path B — Coplay MCP** (community) — for Unity 2022+ ## Repo Structure ```text unity-claude-code-skill/ -├── SKILL.md # Core skill instructions (auto-loaded by Claude Code) +├── SKILL.md # Core skill: setup + operations + workflows ├── README.md # This file ├── LICENSE # MIT -├── verify_setup.sh # macOS/Linux prerequisite checker -├── verify_setup.ps1 # Windows prerequisite checker +├── auto_setup.sh # One-click MCP setup (macOS/Linux) +├── auto_setup.ps1 # One-click MCP setup (Windows) +├── unity_operations.md # Detailed MCP tool reference & code templates +├── verify_setup.sh # Prerequisite checker (macOS/Linux) +├── verify_setup.ps1 # Prerequisite checker (Windows) ├── troubleshooting.md # Common issues & fixes ├── .github/workflows/ci.yml # CI: markdown lint, shellcheck, link check └── i18n/ # Translations @@ -47,11 +55,11 @@ unity-claude-code-skill/ ```bash # User-level skill (available in all projects) -git clone https://github.com//unity-claude-code-skill.git \ +git clone https://github.com/ryan-focus/unity-claude-code-skill.git \ ~/.claude/skills/unity-claude-code-setup # Or project-level skill (available only in this project) -git clone https://github.com//unity-claude-code-skill.git \ +git clone https://github.com/ryan-focus/unity-claude-code-skill.git \ .claude/skills/unity-claude-code-setup ``` @@ -62,36 +70,61 @@ If you only want the core instructions without scripts: ```bash mkdir -p ~/.claude/skills/unity-claude-code-setup curl -o ~/.claude/skills/unity-claude-code-setup/SKILL.md \ - https://raw.githubusercontent.com//unity-claude-code-skill/main/SKILL.md + https://raw.githubusercontent.com/ryan-focus/unity-claude-code-skill/main/SKILL.md ``` -## Usage - -Once installed, just talk to Claude Code naturally: - -- *"Help me set up Claude Code with Unity"* -- *"I want to connect my Unity project to Claude Code via MCP"* -- *"How do I install Coplay MCP for Unity?"* -- *"Set up Unity MCP on Windows"* +## One-Click MCP Setup -Claude Code will automatically load this skill and walk you through the process. +After installing the skill, run the auto-setup script to configure the MCP +connection: -### Run the Verification Script - -After setup, you can verify everything is in place: - -**macOS/Linux:** +**macOS / Linux:** ```bash -bash ~/.claude/skills/unity-claude-code-setup/scripts/verify_setup.sh +cd ~/.claude/skills/unity-claude-code-setup +bash auto_setup.sh --auto # Auto-detect best path +bash auto_setup.sh --path coplay # Force Coplay MCP +bash auto_setup.sh --path unity # Force Unity Official MCP ``` **Windows (PowerShell):** ```powershell -. "$env:USERPROFILE\.claude\skills\unity-claude-code-setup\scripts\verify_setup.ps1" +cd "$env:USERPROFILE\.claude\skills\unity-claude-code-setup" +.\auto_setup.ps1 -Auto # Auto-detect best path +.\auto_setup.ps1 -Path coplay # Force Coplay MCP +.\auto_setup.ps1 -Path unity # Force Unity Official MCP ``` +**Options:** +- `--force` / `-Force` — Remove existing MCP config before re-adding +- `--timeout ` / `-Timeout ` — Custom timeout (default: 720000ms) +- `--coplay-version ` / `-CoplayVersion ` — Coplay server version + +## Usage + +Once installed and connected, just talk to Claude Code naturally: + +**Setup:** +- *"Help me set up Claude Code with Unity"* +- *"Connect my Unity project to Claude Code via MCP"* + +**Operations:** +- *"Create a new scene called GameLevel"* +- *"Add a red cube at position (0, 2, 0)"* +- *"Create a PlayerController script with WASD movement"* +- *"Set up a standard project folder structure"* +- *"Check the Unity console for errors"* + +**Rapid prototyping:** +- *"Help me prototype a ball-rolling game"* +- *"Create a basic 2D platformer"* +- *"Build a main menu UI system"* + +**Diagnostics:** +- *"The MCP connection isn't working, help me fix it"* +- *"Run diagnostics on my Unity setup"* + ## Prerequisites | Tool | Required for | Install | @@ -99,7 +132,7 @@ bash ~/.claude/skills/unity-claude-code-setup/scripts/verify_setup.sh | Claude Code | Both paths | `curl -fsSL https://claude.ai/install.sh \| bash` (macOS/Linux) or `irm https://claude.ai/install.ps1 \| iex` (Windows) | | Unity 6+ | Path A | [unity.com](https://unity.com/download) | | Unity 2022+ | Path B | [unity.com](https://unity.com/download) | -| Python ≥ 3.11 | Path B only | [python.org](https://www.python.org/downloads/) | +| Python >= 3.11 | Path B only | [python.org](https://www.python.org/downloads/) | | Git for Windows | Windows only | [git-scm.com](https://git-scm.com/download/win) | ## Key Resources diff --git a/SKILL.md b/SKILL.md index 0da3f5a..4b68f74 100644 --- a/SKILL.md +++ b/SKILL.md @@ -1,218 +1,356 @@ --- -name: unity-claude-code-setup +name: unity-claude-code-assistant description: > - Step-by-step guide to install Claude Code, connect it to Unity Editor via MCP - (Model Context Protocol), and verify the integration works. Covers both the - Unity official MCP (com.unity.ai.assistant) and the community Coplay MCP. - Supports Windows and macOS. Use this skill whenever the user mentions setting - up Claude Code with Unity, connecting an AI assistant to Unity Editor, - Unity MCP installation, Coplay MCP setup, or wants to use natural-language - commands to control Unity scenes, GameObjects, assets, or scripts through - Claude Code. Also trigger when the user asks about prerequisites for - AI-assisted Unity development, troubleshooting Claude Code + Unity connections, - or comparing Unity MCP vs Coplay MCP. + Complete Unity AI development assistant. Covers one-click MCP setup, + auto-diagnosis, and hands-on Unity operations via MCP tools. + Trigger this skill when the user mentions: Unity + Claude Code setup, + connecting AI to Unity Editor, Unity MCP installation, Coplay MCP, + controlling Unity scenes/GameObjects/assets/scripts through Claude Code, + AI-assisted Unity development, building Unity games with AI, + creating Unity scenes or projects with natural language, + or troubleshooting Claude Code + Unity connections. --- -# Unity + Claude Code + MCP Setup Guide +# Unity + Claude Code — AI Development Assistant -This skill walks you through connecting Claude Code to Unity Editor via MCP so -you can control scenes, assets, scripts, and more with natural language. - -There are **two main paths**. Pick the one that fits the user's situation: - -| Path | When to use | -|------|-------------| -| **Path A – Unity Official MCP** | Unity 6+ with `com.unity.ai.assistant` package. Officially supported by Unity. | -| **Path B – Coplay MCP (community)** | Unity 2022+. More tools, faster iteration, community-driven. | - -If the user is unsure, ask which Unity version they have. Unity 6+ users can -use either path; Unity 2022–2023 users should use Path B. +You are a Unity development assistant connected to Unity Editor via MCP. +This skill covers **setup**, **auto-diagnosis**, and **direct Unity operations**. --- -## Shared Prerequisites +## 1. Quick Setup (One-Click) -Before either path, make sure these are in place: - -### 1. Install Claude Code - -Claude Code requires a paid Anthropic plan (Pro, Max, Team, or Enterprise). +If the MCP connection is not yet configured, use the auto-setup scripts: **macOS / Linux:** ```bash -curl -fsSL https://claude.ai/install.sh | bash +bash auto_setup.sh --auto # Auto-detect best path +bash auto_setup.sh --path coplay # Force Coplay MCP +bash auto_setup.sh --path unity # Force Unity Official MCP ``` **Windows (PowerShell):** ```powershell -irm https://claude.ai/install.ps1 | iex +.\auto_setup.ps1 -Auto # Auto-detect best path +.\auto_setup.ps1 -Path coplay # Force Coplay MCP +.\auto_setup.ps1 -Path unity # Force Unity Official MCP ``` -> Windows also requires **Git for Windows** to be installed. - -**Verify:** +**Options:** +- `--force` / `-Force` — Remove existing config before re-adding +- `--timeout ` / `-Timeout ` — Custom timeout (default: 720000) -```bash -claude --version -``` - -After first launch, run `claude` and follow the browser prompts to authenticate. +### Path A vs Path B -### 2. Verify Unity is installed +| | Path A — Unity Official MCP | Path B — Coplay MCP | +|---|---|---| +| Package | `com.unity.ai.assistant` | `coplay-mcp-server` | +| Unity | 6+ | 2022+ | +| Tools | Fewer, officially supported | More tools, community-driven | +| Setup | Relay binary + approve connection | Python 3.11 + uvx | -- Path A requires **Unity 6 (6000.0)** or later. -- Path B requires **Unity 2022** or later. +If user is unsure, ask their Unity version. Unity 6+ → either path. Unity 2022–2023 → Path B. --- -## Path A – Unity Official MCP +## 2. Manual Setup -### A1. Install the AI Assistant package +Use this only if the auto-setup script fails. -In Unity, go to **Window > Package Manager**, click **+**, choose -**Add package by name**, and enter: +### Shared Prerequisites -```text -com.unity.ai.assistant -``` - -### A2. Start the Unity Bridge +1. **Claude Code** — requires paid Anthropic plan -1. Go to **Edit > Project Settings > AI > Unity MCP**. -2. Confirm the **Unity Bridge** status shows **Running** (green). -3. If it shows **Stopped**, click **Start**. + ```bash + # macOS/Linux + curl -fsSL https://claude.ai/install.sh | bash + # Windows + irm https://claude.ai/install.ps1 | iex + ``` -The relay binary is auto-installed to `~/.unity/relay/`. +2. **Unity** — Path A needs Unity 6+, Path B needs Unity 2022+ -### A3. Configure Claude Code +### Path A — Unity Official MCP -**Option 1 – Auto-configure (recommended):** -In Unity's **Project Settings > AI > Unity MCP > Integrations**, find -**Claude Code** and click **Configure**. +1. Install `com.unity.ai.assistant` via Package Manager +2. Edit > Project Settings > AI > Unity MCP → ensure Bridge is **Running** +3. Configure Claude Code: -**Option 2 – Manual:** + ```bash + claude mcp add unity-mcp -- --mcp + ``` -Run in terminal: + | Platform | Relay path | + |----------|-----------| + | macOS ARM | `~/.unity/relay/relay_mac_arm64.app/Contents/MacOS/relay_mac_arm64` | + | macOS Intel | `~/.unity/relay/relay_mac_x64.app/Contents/MacOS/relay_mac_x64` | + | Windows | `%USERPROFILE%\.unity\relay\relay_win.exe` | -```bash -claude mcp add unity-mcp -- --mcp -``` +4. In Unity: accept the pending connection -Replace `` with the correct path for your platform: +### Path B — Coplay MCP -| Platform | Relay path | -|----------|-----------| -| macOS (Apple Silicon) | `~/.unity/relay/relay_mac_arm64.app/Contents/MacOS/relay_mac_arm64` | -| macOS (Intel) | `~/.unity/relay/relay_mac_x64.app/Contents/MacOS/relay_mac_x64` | -| Windows | `%USERPROFILE%\.unity\relay\relay_win.exe` | +1. Install Python ≥ 3.11 +2. In Unity: add package from git URL `https://github.com/CoplayDev/unity-plugin.git#beta` +3. Configure Claude Code: -### A4. Approve the connection + ```bash + claude mcp add --scope user --transport stdio coplay-mcp \ + --env MCP_TOOL_TIMEOUT=720000 \ + -- uvx --python ">=3.11" coplay-mcp-server@1.5.5 + ``` -1. Back in Unity: **Edit > Project Settings > AI > Unity MCP**. -2. Under **Pending Connections**, review and click **Accept**. +--- -Previously approved clients reconnect automatically. +## 3. Auto-Diagnosis -### A5. Test +When the user reports connection issues or something isn't working, follow +this diagnostic sequence: -In Claude Code, try: +### Step 1 — Check MCP configuration -```text -Read the Unity console messages and summarize any warnings or errors. +```bash +claude mcp list ``` -If Claude can invoke `Unity_ReadConsole`, the setup is complete. +Verify the target MCP server (unity-mcp or coplay-mcp) is listed. ---- +### Step 2 — Test MCP connection + +Try a simple tool call: +- **Coplay:** `list_editors` — should return open Unity instances +- **Unity Official:** `Unity_ReadConsole` — should return console messages -## Path B – Coplay MCP (Community) +### Step 3 — Common failure modes -### B1. Install Python 3.11+ +| Symptom | Likely cause | Fix | +|---------|-------------|-----| +| MCP not in list | Not configured | Run `auto_setup.sh --auto` | +| "connecting" forever | Server not running | Restart Claude Code; ensure Unity is open | +| Connection refused | Unity Bridge stopped | Project Settings > AI > Unity MCP > Start | +| Timeout errors | Operation too slow | Increase `MCP_TOOL_TIMEOUT` to 1800000 | +| "python not found" | Python < 3.11 or missing | Install Python ≥ 3.11 | +| "uvx not found" | uv not installed | `pip install uv` | +| Tool call fails | Wrong tool name | Run `list available MCP tools` to discover exact names | +| macOS PATH issue | Unity launched from Finder | Launch Unity Hub from Terminal: `open -a "Unity Hub"` | -Coplay's MCP server requires Python ≥ 3.11. +### Step 4 — Nuclear reset -**Verify:** +If nothing works, remove and re-add: ```bash -python3 --version # macOS/Linux -python --version # Windows +claude mcp remove coplay-mcp # or unity-mcp +bash auto_setup.sh --path coplay --force ``` -If not installed: +Refer to `troubleshooting.md` for additional details. -- macOS: `brew install python@3.11` -- Windows: download from +--- -### B2. Install the Coplay Unity package +## 4. Unity Operations — How to Use MCP Tools -1. Open your Unity project. -2. **Window > Package Manager > + > Add package from git URL** -3. Enter: +When the MCP connection is active, you can directly control Unity. +Read `unity_operations.md` for the complete tool reference and code templates. - ```text - https://github.com/CoplayDev/unity-plugin.git#beta - ``` +### Key Principles -4. Ensure Coplay is enabled and running in the Editor. +1. **Discover tools first.** At the start of each session, list available MCP + tools to know what operations are supported. +2. **Use run_code / ExecuteCode for anything complex.** When a dedicated tool + doesn't exist, write C# code and execute it directly in the editor. +3. **Verify after each action.** Read the console and check the hierarchy after + creating or modifying objects. +4. **Batch operations.** For multiple objects, write one C# script instead of + calling tools repeatedly. -### B3. Add Coplay MCP to Claude Code +### Scene Management -```bash -claude mcp add \ - --scope user \ - --transport stdio \ - coplay-mcp \ - --env MCP_TOOL_TIMEOUT=720000 \ - -- uvx --python ">=3.11" coplay-mcp-server@1.5.5 +**Create a new scene:** +``` +1. execute_menu_item("File/New Scene") +2. Save via run_code: + EditorSceneManager.SaveScene( + SceneManager.GetActiveScene(), "Assets/Scenes/.unity"); ``` -> On Windows, run this in PowerShell. If `uvx` is not found, install it with -> `pip install uv` first. - -### B4. Verify +**Get scene contents:** +``` +get_scene_hierarchy → returns full object tree +``` -```bash -claude mcp list +**Save scene:** +``` +execute_menu_item("File/Save") ``` -You should see `coplay-mcp` in the list. +### GameObject Operations + +**Create primitives (Cube, Sphere, Capsule, Plane, Cylinder):** +``` +create_primitive("Cube", name="MyCube") +set_component_property("MyCube", "Transform", "position", {x:0, y:1, z:0}) +``` -### B5. Test +**Create hierarchy:** +``` +1. Create parent: create_gameobject("Player") +2. Create children and parent them under Player +3. Set transforms for each child +``` -Open your Unity project, then in Claude Code: +**Add components:** +``` +add_component("Player", "Rigidbody") +add_component("Player", "CharacterController") +set_component_property("Player", "Rigidbody", "mass", 2.0) +``` -```text -List all open Unity editors +### Script Development + +When the user asks to create scripts, generate the full C# file and use +`create_script` or `run_code` to write it into the project: + +```csharp +// Write script file to Assets/Scripts/ +run_code(@" + System.IO.Directory.CreateDirectory(""Assets/Scripts""); + System.IO.File.WriteAllText(""Assets/Scripts/PlayerController.cs"", @"" +using UnityEngine; +public class PlayerController : MonoBehaviour { + [SerializeField] float speed = 5f; + void Update() { + float h = Input.GetAxis(""Horizontal""); + float v = Input.GetAxis(""Vertical""); + transform.Translate(new Vector3(h, 0, v) * speed * Time.deltaTime); + } +} +""); + AssetDatabase.Refresh(); +"); ``` -Then try: +Common script patterns (see `unity_operations.md` for full templates): +- **PlayerController** — WASD movement with CharacterController +- **GameManager** — Singleton pattern with DontDestroyOnLoad +- **HealthBarUI** — Slider-based UI with color gradient +- **CameraFollow** — Smooth follow with offset +- **SceneLoader** — Async scene transitions with loading screen + +### Materials and Visuals + +```csharp +// Create and assign a colored material +run_code(@" + var obj = GameObject.Find(""MyCube""); + var mat = new Material(Shader.Find(""Standard"")); + mat.color = Color.red; + obj.GetComponent().material = mat; +"); +``` -```text -Create a red cube at position (0, 1, 0) in the current Unity scene +### Asset Structure + +Set up a professional project structure: + +```csharp +run_code(@" + string[] folders = { + ""Assets/Scripts"", ""Assets/Scenes"", ""Assets/Prefabs"", + ""Assets/Materials"", ""Assets/Textures"", ""Assets/Audio"", + ""Assets/Animations"", ""Assets/Fonts"", ""Assets/Resources"" + }; + foreach (var f in folders) { + var parts = f.Split('/'); + var parent = parts[0]; + for (int i = 1; i < parts.Length; i++) { + var next = parent + ""/"" + parts[i]; + if (!AssetDatabase.IsValidFolder(next)) + AssetDatabase.CreateFolder(parent, parts[i]); + parent = next; + } + } + AssetDatabase.Refresh(); +"); ``` ---- +### Debugging -## Troubleshooting +**Read console messages:** +``` +get_console_logs or Unity_ReadConsole +→ Summarize errors and warnings, suggest fixes +``` -Read `references/troubleshooting.md` for common issues, including: +**Find missing scripts:** +```csharp +run_code(@" + foreach (var go in Resources.FindObjectsOfTypeAll()) { + foreach (var c in go.GetComponents()) { + if (c == null) Debug.LogWarning($""Missing script on: {go.name}""); + } + } +"); +``` + +--- -- `claude` command not found -- MCP server stuck on "connecting" -- Unity not detecting the MCP client -- macOS PATH issues when Unity is launched from Finder -- Timeout errors on large operations -- Windows-specific PowerShell issues +## 5. Rapid Prototype Workflows + +When the user asks to build something quickly, follow these structured workflows. + +### 3D Ball-Rolling Game + +1. Create scene "GameLevel" +2. Create Floor (Plane, scale 5x5) +3. Create Player (Sphere + Rigidbody at y=0.5) +4. Create BallController.cs — force-based WASD movement +5. Create collectible items (small cubes with trigger colliders) +6. Create Collectible.cs — OnTriggerEnter → destroy + add score +7. Create ScoreManager.cs singleton +8. Create UI Canvas with score text +9. Add CameraFollow.cs for smooth tracking +10. Set up lighting and skybox + +### 2D Platformer + +1. Create 2D scene +2. Create ground sprite / tilemap +3. Create Player (sprite + Rigidbody2D + BoxCollider2D) +4. Create PlatformController2D.cs — move + jump + ground check +5. Create platforms at various heights +6. Add CameraFollow2D.cs +7. Add death zone below platforms +8. Add score/lives UI + +### FPS Prototype + +1. Create scene with terrain or floor +2. Create Player (Capsule + CharacterController + Camera as child) +3. Create FPSController.cs — WASD + mouse look +4. Create simple obstacles (walls, crates) +5. Add shooting mechanic (raycast or projectile) +6. Add enemy targets with health +7. Add crosshair UI and ammo counter + +### UI Menu System + +1. Create Canvas (Screen Space - Overlay) +2. Create title text (TextMeshPro) +3. Create buttons: Start, Settings, Quit +4. Create MainMenuController.cs for button handlers +5. Create settings panel with volume slider +6. Create scene transition logic --- -## Post-Setup Tips +## 6. Post-Setup Tips -- Run `claude /init` in your Unity project root to generate a `CLAUDE.md` that - describes your project conventions to Claude Code. -- Use the `@` symbol in Claude Code to reference specific files, e.g. - `@PlayerController.cs`. -- For Coplay MCP, increase `MCP_TOOL_TIMEOUT` if you hit timeout errors on - long operations (default is 720000ms = 12 min). +- Run `claude /init` in your Unity project root to generate a `CLAUDE.md` + describing your project conventions. +- Use `@` in Claude Code to reference files: `@PlayerController.cs`. +- For large operations, increase `MCP_TOOL_TIMEOUT` (default 12 min). +- Save scenes frequently — trigger via `execute_menu_item("File/Save")`. +- Use `run_code` / `ExecuteCode` as a Swiss Army knife for any operation + that doesn't have a dedicated MCP tool. diff --git a/auto_setup.ps1 b/auto_setup.ps1 new file mode 100644 index 0000000..b17beda --- /dev/null +++ b/auto_setup.ps1 @@ -0,0 +1,231 @@ +# auto_setup.ps1 — One-click MCP setup for Unity + Claude Code (Windows) +# Usage: +# .\auto_setup.ps1 -Path coplay # Install Coplay MCP +# .\auto_setup.ps1 -Path unity # Configure Unity Official MCP +# .\auto_setup.ps1 -Auto # Auto-detect best path + +param( + [ValidateSet("coplay", "unity", "")] + [string]$Path = "", + [switch]$Auto, + [int]$Timeout = 720000, + [string]$CoplayVersion = "1.5.5", + [switch]$Force, + [switch]$Help +) + +function Write-Pass { param($msg) Write-Host "[OK] $msg" -ForegroundColor Green } +function Write-Warn { param($msg) Write-Host "[WARN] $msg" -ForegroundColor Yellow } +function Write-Fail { param($msg) Write-Host "[FAIL] $msg" -ForegroundColor Red } +function Write-Info { param($msg) Write-Host "[INFO] $msg" -ForegroundColor Cyan } + +if ($Help) { + Write-Host "Usage: .\auto_setup.ps1 [OPTIONS]" + Write-Host "" + Write-Host "Options:" + Write-Host " -Path coplay|unity Choose MCP path" + Write-Host " -Auto Auto-detect best MCP path" + Write-Host " -Timeout MS Coplay MCP timeout in ms (default: 720000)" + Write-Host " -CoplayVersion VER Coplay MCP server version (default: 1.5.5)" + Write-Host " -Force Remove existing MCP config before setup" + Write-Host " -Help Show this help" + exit 0 +} + +if (-not $Path -and -not $Auto) { + Write-Fail "Please specify -Path coplay, -Path unity, or -Auto" + Write-Host "" + Write-Host "Usage: .\auto_setup.ps1 -Path coplay|unity" + Write-Host " .\auto_setup.ps1 -Auto" + exit 1 +} + +Write-Host "" +Write-Host "==========================================" -ForegroundColor Cyan +Write-Host " Unity + Claude Code — Auto Setup" -ForegroundColor Cyan +Write-Host "==========================================" -ForegroundColor Cyan +Write-Host "" + +# --- Step 1: Check Claude Code --- +Write-Info "Checking prerequisites..." + +try { + $claudeVer = claude --version 2>$null + if ($claudeVer) { + Write-Pass "Claude Code found: $claudeVer" + } else { + throw "not found" + } +} catch { + Write-Fail "Claude Code not found." + Write-Host " Install: irm https://claude.ai/install.ps1 | iex" + exit 1 +} + +# Check Git +try { + $gitVer = git --version 2>$null + if ($gitVer) { + Write-Pass "Git found: $gitVer" + } else { + throw "not found" + } +} catch { + Write-Fail "Git for Windows not found (required for Claude Code)." + Write-Host " Download: https://git-scm.com/download/win" + exit 1 +} + +# --- Step 2: Auto-detect --- +if ($Auto) { + Write-Info "Auto-detecting best MCP path..." + $relayDir = Join-Path $env:USERPROFILE ".unity\relay" + $relayExe = Join-Path $relayDir "relay_win.exe" + + if (Test-Path $relayExe) { + Write-Info "Unity relay binary detected — using Unity Official MCP (Path A)" + $Path = "unity" + } else { + Write-Info "No Unity relay found — using Coplay MCP (Path B)" + $Path = "coplay" + } +} + +# --- Path A: Unity Official MCP --- +function Setup-UnityOfficial { + Write-Info "Setting up Unity Official MCP..." + Write-Host "" + + $relayDir = Join-Path $env:USERPROFILE ".unity\relay" + $relayExe = Join-Path $relayDir "relay_win.exe" + + if (-not (Test-Path $relayExe)) { + Write-Fail "Unity relay binary not found at $relayExe" + Write-Host "" + Write-Host " To fix this:" + Write-Host " 1. Open Unity 6+ and install com.unity.ai.assistant via Package Manager" + Write-Host " 2. Go to Edit > Project Settings > AI > Unity MCP" + Write-Host " 3. Make sure Unity Bridge shows 'Running'" + Write-Host " 4. Re-run this script" + exit 1 + } + + Write-Pass "Relay binary found: $relayExe" + + if ($Force) { + Write-Info "Removing existing unity-mcp config..." + claude mcp remove unity-mcp 2>$null + } + + Write-Info "Configuring Claude Code MCP connection..." + try { + claude mcp add unity-mcp -- $relayExe --mcp 2>$null + Write-Pass "unity-mcp added to Claude Code" + } catch { + Write-Warn "Failed to add unity-mcp. It may already exist. Use -Force to overwrite." + return + } + + Write-Host "" + Write-Pass "Unity Official MCP setup complete!" + Write-Host "" + Write-Host " Next steps:" + Write-Host " 1. Open your Unity 6+ project" + Write-Host " 2. Go to Edit > Project Settings > AI > Unity MCP" + Write-Host " 3. Accept the pending connection from Claude Code" + Write-Host " 4. Test: run 'claude' and ask it to read the Unity console" +} + +# --- Path B: Coplay MCP --- +function Setup-Coplay { + Write-Info "Setting up Coplay MCP..." + Write-Host "" + + # Check Python >= 3.11 + try { + $pyVer = python --version 2>$null + if ($pyVer) { + $pyMinor = python -c "import sys; print(sys.version_info.minor)" 2>$null + if ([int]$pyMinor -ge 11) { + Write-Pass "Python found: $pyVer (>= 3.11)" + } else { + Write-Fail "Python >= 3.11 required, found: $pyVer" + Write-Host " Download from: https://www.python.org/downloads/" + exit 1 + } + } else { + throw "not found" + } + } catch { + Write-Fail "Python not found." + Write-Host " Download from: https://www.python.org/downloads/" + exit 1 + } + + # Check/install uvx + try { + Get-Command uvx -ErrorAction Stop | Out-Null + Write-Pass "uvx found" + } catch { + Write-Info "uvx not found. Installing uv..." + try { + pip install uv 2>$null + Get-Command uvx -ErrorAction Stop | Out-Null + Write-Pass "uvx installed successfully" + } catch { + Write-Fail "Could not install uvx automatically." + Write-Host " Install manually: pip install uv" + exit 1 + } + } + + if ($Force) { + Write-Info "Removing existing coplay-mcp config..." + claude mcp remove coplay-mcp 2>$null + } + + Write-Info "Configuring Claude Code MCP connection..." + try { + claude mcp add ` + --scope user ` + --transport stdio ` + coplay-mcp ` + --env "MCP_TOOL_TIMEOUT=$Timeout" ` + -- uvx --python ">=3.11" "coplay-mcp-server@$CoplayVersion" 2>$null + Write-Pass "coplay-mcp added to Claude Code" + } catch { + Write-Warn "Failed to add coplay-mcp. It may already exist. Use -Force to overwrite." + return + } + + Write-Host "" + Write-Pass "Coplay MCP setup complete!" + Write-Host "" + Write-Host " Next steps:" + Write-Host " 1. Open your Unity project (2022+)" + Write-Host " 2. Install Coplay: Window > Package Manager > + > Add from git URL" + Write-Host " URL: https://github.com/CoplayDev/unity-plugin.git#beta" + Write-Host " 3. Enable Coplay in the Editor" + Write-Host " 4. Test: run 'claude' and ask it to list open Unity editors" +} + +# --- Execute --- +switch ($Path) { + "unity" { Setup-UnityOfficial } + "coplay" { Setup-Coplay } +} + +# --- Verify --- +Write-Host "" +Write-Info "Verifying MCP configuration..." +Write-Host "--- Configured MCP Servers ---" -ForegroundColor Cyan +try { + claude mcp list 2>$null +} catch { + Write-Warn "Could not list MCP servers." +} + +Write-Host "" +Write-Host "==========================================" -ForegroundColor Cyan +Write-Host " Setup complete!" -ForegroundColor Cyan +Write-Host "==========================================" -ForegroundColor Cyan diff --git a/auto_setup.sh b/auto_setup.sh new file mode 100644 index 0000000..340b348 --- /dev/null +++ b/auto_setup.sh @@ -0,0 +1,272 @@ +#!/usr/bin/env bash +# auto_setup.sh — One-click MCP setup for Unity + Claude Code +# Supports both Unity Official MCP (Path A) and Coplay MCP (Path B) +# Usage: +# bash auto_setup.sh --path coplay # Install Coplay MCP +# bash auto_setup.sh --path unity # Configure Unity Official MCP +# bash auto_setup.sh --auto # Auto-detect best path + +set -euo pipefail + +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +CYAN='\033[0;36m' +NC='\033[0m' + +pass() { echo -e "${GREEN}[OK]${NC} $1"; } +warn() { echo -e "${YELLOW}[WARN]${NC} $1"; } +fail() { echo -e "${RED}[FAIL]${NC} $1"; } +info() { echo -e "${CYAN}[INFO]${NC} $1"; } + +MCP_PATH="" +COPLAY_VERSION="1.5.5" +MCP_TIMEOUT=720000 +FORCE=false + +usage() { + echo "Usage: bash auto_setup.sh [OPTIONS]" + echo "" + echo "Options:" + echo " --path coplay|unity Choose MCP path (required unless --auto)" + echo " --auto Auto-detect best MCP path" + echo " --timeout MS Coplay MCP timeout in ms (default: 720000)" + echo " --coplay-version VER Coplay MCP server version (default: $COPLAY_VERSION)" + echo " --force Remove existing MCP config before setup" + echo " -h, --help Show this help" + exit 0 +} + +# --- Parse arguments --- +while [[ $# -gt 0 ]]; do + case "$1" in + --path) + MCP_PATH="$2"; shift 2 ;; + --auto) + MCP_PATH="auto"; shift ;; + --timeout) + MCP_TIMEOUT="$2"; shift 2 ;; + --coplay-version) + COPLAY_VERSION="$2"; shift 2 ;; + --force) + FORCE=true; shift ;; + -h|--help) + usage ;; + *) + fail "Unknown option: $1"; usage ;; + esac +done + +if [[ -z "$MCP_PATH" ]]; then + fail "Please specify --path coplay, --path unity, or --auto" + echo "" + usage +fi + +echo "" +echo "==========================================" +echo " Unity + Claude Code — Auto Setup" +echo "==========================================" +echo "" + +# --- Step 1: Check Claude Code --- +info "Checking prerequisites..." + +if ! command -v claude &>/dev/null; then + fail "Claude Code not found." + echo " Install with: curl -fsSL https://claude.ai/install.sh | bash" + exit 1 +fi +CLAUDE_VER=$(claude --version 2>/dev/null || echo "unknown") +pass "Claude Code found: $CLAUDE_VER" + +# --- Step 2: Auto-detect path if needed --- +if [[ "$MCP_PATH" == "auto" ]]; then + info "Auto-detecting best MCP path..." + RELAY_DIR="$HOME/.unity/relay" + + if [[ -d "$RELAY_DIR" ]]; then + # Check for relay binary + HAS_RELAY=false + if [[ "$(uname)" == "Darwin" ]]; then + if [[ -f "$RELAY_DIR/relay_mac_arm64.app/Contents/MacOS/relay_mac_arm64" ]] || \ + [[ -f "$RELAY_DIR/relay_mac_x64.app/Contents/MacOS/relay_mac_x64" ]]; then + HAS_RELAY=true + fi + else + if [[ -f "$RELAY_DIR/relay_linux" ]]; then + HAS_RELAY=true + fi + fi + + if [[ "$HAS_RELAY" == true ]]; then + info "Unity relay binary detected — using Unity Official MCP (Path A)" + MCP_PATH="unity" + else + info "Relay directory exists but no binary — falling back to Coplay MCP (Path B)" + MCP_PATH="coplay" + fi + else + info "No Unity relay found — using Coplay MCP (Path B)" + MCP_PATH="coplay" + fi +fi + +# --- Path A: Unity Official MCP --- +setup_unity_official() { + info "Setting up Unity Official MCP..." + echo "" + + RELAY_DIR="$HOME/.unity/relay" + RELAY_BIN="" + + if [[ "$(uname)" == "Darwin" ]]; then + # macOS — detect ARM vs Intel + if [[ -f "$RELAY_DIR/relay_mac_arm64.app/Contents/MacOS/relay_mac_arm64" ]]; then + RELAY_BIN="$RELAY_DIR/relay_mac_arm64.app/Contents/MacOS/relay_mac_arm64" + elif [[ -f "$RELAY_DIR/relay_mac_x64.app/Contents/MacOS/relay_mac_x64" ]]; then + RELAY_BIN="$RELAY_DIR/relay_mac_x64.app/Contents/MacOS/relay_mac_x64" + fi + else + # Linux + if [[ -f "$RELAY_DIR/relay_linux" ]]; then + RELAY_BIN="$RELAY_DIR/relay_linux" + fi + fi + + if [[ -z "$RELAY_BIN" ]]; then + fail "Unity relay binary not found at $RELAY_DIR" + echo "" + echo " To fix this:" + echo " 1. Open Unity 6+ and install com.unity.ai.assistant via Package Manager" + echo " 2. Go to Edit > Project Settings > AI > Unity MCP" + echo " 3. Make sure Unity Bridge shows 'Running'" + echo " 4. Re-run this script" + exit 1 + fi + + pass "Relay binary found: $RELAY_BIN" + + # Remove existing config if --force + if [[ "$FORCE" == true ]]; then + info "Removing existing unity-mcp config..." + claude mcp remove unity-mcp 2>/dev/null || true + fi + + # Add MCP server + info "Configuring Claude Code MCP connection..." + if claude mcp add unity-mcp -- "$RELAY_BIN" --mcp 2>/dev/null; then + pass "unity-mcp added to Claude Code" + else + warn "Failed to add unity-mcp. It may already exist. Use --force to overwrite." + return 1 + fi + + echo "" + pass "Unity Official MCP setup complete!" + echo "" + echo " Next steps:" + echo " 1. Open your Unity 6+ project" + echo " 2. Go to Edit > Project Settings > AI > Unity MCP" + echo " 3. Accept the pending connection from Claude Code" + echo " 4. Test: run 'claude' and ask it to read the Unity console" +} + +# --- Path B: Coplay MCP --- +setup_coplay() { + info "Setting up Coplay MCP..." + echo "" + + # Check Python >= 3.11 + if command -v python3 &>/dev/null; then + PY_VER=$(python3 --version 2>/dev/null) + PY_MINOR=$(python3 -c 'import sys; print(sys.version_info.minor)' 2>/dev/null || echo "0") + if [[ "$PY_MINOR" -ge 11 ]]; then + pass "Python found: $PY_VER (>= 3.11)" + else + fail "Python >= 3.11 required, found: $PY_VER" + echo " Install: brew install python@3.11 (macOS) or download from python.org" + exit 1 + fi + else + fail "Python3 not found." + echo " Install: brew install python@3.11 (macOS) or download from python.org" + exit 1 + fi + + # Check/install uvx + if command -v uvx &>/dev/null; then + pass "uvx found" + else + info "uvx not found. Installing uv..." + if command -v pip3 &>/dev/null; then + pip3 install uv 2>/dev/null + elif command -v pip &>/dev/null; then + pip install uv 2>/dev/null + else + fail "pip not found. Cannot install uv automatically." + echo " Install manually: pip install uv" + exit 1 + fi + + if command -v uvx &>/dev/null; then + pass "uvx installed successfully" + else + fail "uvx still not found after installing uv." + echo " Try: pip install uv && hash -r" + exit 1 + fi + fi + + # Remove existing config if --force + if [[ "$FORCE" == true ]]; then + info "Removing existing coplay-mcp config..." + claude mcp remove coplay-mcp 2>/dev/null || true + fi + + # Add MCP server + info "Configuring Claude Code MCP connection..." + if claude mcp add \ + --scope user \ + --transport stdio \ + coplay-mcp \ + --env "MCP_TOOL_TIMEOUT=$MCP_TIMEOUT" \ + -- uvx --python ">=3.11" "coplay-mcp-server@$COPLAY_VERSION" 2>/dev/null; then + pass "coplay-mcp added to Claude Code" + else + warn "Failed to add coplay-mcp. It may already exist. Use --force to overwrite." + return 1 + fi + + echo "" + pass "Coplay MCP setup complete!" + echo "" + echo " Next steps:" + echo " 1. Open your Unity project (2022+)" + echo " 2. Install Coplay package: Window > Package Manager > + > Add from git URL" + echo " URL: https://github.com/CoplayDev/unity-plugin.git#beta" + echo " 3. Enable Coplay in the Editor" + echo " 4. Test: run 'claude' and ask it to list open Unity editors" +} + +# --- Execute --- +case "$MCP_PATH" in + unity) + setup_unity_official ;; + coplay) + setup_coplay ;; + *) + fail "Invalid path: $MCP_PATH (expected 'coplay' or 'unity')" + exit 1 ;; +esac + +# --- Verify --- +echo "" +info "Verifying MCP configuration..." +echo "--- Configured MCP Servers ---" +claude mcp list 2>/dev/null || warn "Could not list MCP servers." + +echo "" +echo "==========================================" +echo " Setup complete!" +echo "==========================================" diff --git a/unity_operations.md b/unity_operations.md new file mode 100644 index 0000000..6afddeb --- /dev/null +++ b/unity_operations.md @@ -0,0 +1,495 @@ +# Unity Operations Guide — MCP Tool Reference + +This document is the operational playbook for Claude Code when connected to +Unity via MCP. It maps common user requests to specific MCP tool sequences. + +Claude Code: read this file when the user wants to perform Unity operations +after the MCP connection is established. + +--- + +## Tool Availability by MCP Path + +| Operation | Coplay MCP | Unity Official MCP | +|-----------|-----------|-------------------| +| List editors | `list_editors` | — | +| Read console | `get_console_logs` | `Unity_ReadConsole` | +| Scene hierarchy | `get_scene_hierarchy` | `Unity_GetHierarchy` | +| Create GameObject | `create_gameobject` | `Unity_CreateGameObject` | +| Create primitive | `create_primitive` | `Unity_CreatePrimitive` | +| Add component | `add_component` | `Unity_AddComponent` | +| Set property | `set_component_property` | `Unity_SetProperty` | +| Execute menu item | `execute_menu_item` | `Unity_ExecuteMenuItem` | +| Create C# script | `create_script` | — | +| Run C# code | `run_code` / `execute_code` | `Unity_ExecuteCode` | +| Select object | `select_gameobject` | `Unity_SelectGameObject` | +| Delete object | `delete_gameobject` | `Unity_DeleteGameObject` | +| Get/set transform | `set_component_property` | `Unity_SetProperty` | +| Get project info | `get_project_info` | — | +| Import asset | `import_asset` | — | +| Create material | via `run_code` | via `Unity_ExecuteCode` | + +> **Note:** Tool names may vary by version. Use `claude mcp list-tools` or +> ask Claude to list available MCP tools to discover the exact names. + +--- + +## Scene Management + +### Create a New Scene + +``` +User: "Create a new scene called MainMenu" + +Steps: +1. Execute menu item: File > New Scene +2. Save scene to Assets/Scenes/MainMenu.unity +3. Verify scene is active +``` + +**Coplay MCP approach:** +``` +execute_menu_item("File/New Scene") +run_code(" + UnityEditor.SceneManagement.EditorSceneManager.SaveScene( + UnityEngine.SceneManagement.SceneManager.GetActiveScene(), + \"Assets/Scenes/MainMenu.unity\" + ); +") +``` + +**Unity Official MCP approach:** +``` +Unity_ExecuteMenuItem("File/New Scene") +Unity_ExecuteCode(" + EditorSceneManager.SaveScene( + SceneManager.GetActiveScene(), + \"Assets/Scenes/MainMenu.unity\" + ); +") +``` + +### List All Objects in Scene + +``` +User: "What's in the current scene?" + +Steps: +1. Get scene hierarchy +2. Format and present the tree structure +``` + +### Save Current Scene + +``` +execute_menu_item("File/Save") or Ctrl+S equivalent +``` + +--- + +## GameObject Operations + +### Create Basic Objects + +``` +User: "Create a red cube at (0, 2, 0)" + +Steps: +1. Create a primitive cube +2. Set its position to (0, 2, 0) +3. Create a red material +4. Assign the material to the cube +``` + +**Coplay MCP approach:** +``` +create_primitive("Cube", name="RedCube") +set_component_property("RedCube", "Transform", "position", {"x":0, "y":2, "z":0}) +run_code(" + var cube = GameObject.Find(\"RedCube\"); + var renderer = cube.GetComponent(); + var mat = new Material(Shader.Find(\"Standard\")); + mat.color = Color.red; + renderer.material = mat; +") +``` + +### Create Complex Hierarchies + +``` +User: "Create a player character with a body, head, and two arms" + +Steps: +1. Create empty parent: "Player" +2. Create child primitive Capsule: "Body" at (0, 1, 0) +3. Create child primitive Sphere: "Head" at (0, 2, 0) +4. Create child primitive Cube: "LeftArm" at (-0.7, 1.2, 0), scale (0.3, 0.8, 0.3) +5. Create child primitive Cube: "RightArm" at (0.7, 1.2, 0), scale (0.3, 0.8, 0.3) +6. Parent all children under "Player" +``` + +### Add Components + +``` +User: "Add a Rigidbody to the Player" + +Steps: +1. Find the target GameObject +2. Add Rigidbody component +3. Optionally configure mass, drag, constraints +``` + +--- + +## Script Development + +### Create a MonoBehaviour Script + +``` +User: "Create a PlayerController script that handles WASD movement" + +Steps: +1. Generate the C# code +2. Create the script file at Assets/Scripts/PlayerController.cs +3. Attach it to the target GameObject +``` + +**Template — PlayerController.cs:** +```csharp +using UnityEngine; + +public class PlayerController : MonoBehaviour +{ + [SerializeField] private float moveSpeed = 5f; + [SerializeField] private float rotationSpeed = 120f; + + private CharacterController _controller; + + private void Awake() + { + _controller = GetComponent(); + } + + private void Update() + { + float h = Input.GetAxis("Horizontal"); + float v = Input.GetAxis("Vertical"); + + Vector3 move = transform.forward * v + transform.right * h; + _controller.Move(move * (moveSpeed * Time.deltaTime)); + + if (h != 0f) + { + transform.Rotate(0f, h * rotationSpeed * Time.deltaTime, 0f); + } + } +} +``` + +### Create a Singleton Manager + +``` +User: "Create a GameManager singleton" +``` + +**Template — GameManager.cs:** +```csharp +using UnityEngine; + +public class GameManager : MonoBehaviour +{ + public static GameManager Instance { get; private set; } + + [SerializeField] private int targetFrameRate = 60; + + private void Awake() + { + if (Instance != null && Instance != this) + { + Destroy(gameObject); + return; + } + Instance = this; + DontDestroyOnLoad(gameObject); + Application.targetFrameRate = targetFrameRate; + } +} +``` + +### Create a UI Controller + +``` +User: "Create a health bar UI script" +``` + +**Template — HealthBarUI.cs:** +```csharp +using UnityEngine; +using UnityEngine.UI; + +public class HealthBarUI : MonoBehaviour +{ + [SerializeField] private Slider healthSlider; + [SerializeField] private Image fillImage; + [SerializeField] private Color fullHealthColor = Color.green; + [SerializeField] private Color lowHealthColor = Color.red; + + public void SetHealth(float current, float max) + { + float ratio = Mathf.Clamp01(current / max); + healthSlider.value = ratio; + fillImage.color = Color.Lerp(lowHealthColor, fullHealthColor, ratio); + } +} +``` + +--- + +## Materials and Visuals + +### Create and Assign Materials + +``` +User: "Make the floor a wooden texture" + +Approach (via run_code / ExecuteCode): +1. Create a new Material with Standard shader +2. Set main texture if available, or set color +3. Assign to target renderer +``` + +**Code pattern:** +```csharp +var floor = GameObject.Find("Floor"); +var renderer = floor.GetComponent(); +var mat = new Material(Shader.Find("Standard")); +mat.color = new Color(0.55f, 0.35f, 0.17f); // wood-like brown +renderer.material = mat; +``` + +### Setup Basic Lighting + +``` +User: "Set up a basic 3-point lighting" + +Steps: +1. Create Directional Light "KeyLight" — rotation (50, -30, 0), intensity 1.0 +2. Create Directional Light "FillLight" — rotation (30, 120, 0), intensity 0.5 +3. Create Directional Light "BackLight" — rotation (-20, 180, 0), intensity 0.3 +``` + +### Set Skybox + +```csharp +// Via run_code +RenderSettings.skybox = Resources.Load("Skybox/DefaultSkybox"); +``` + +--- + +## Asset Management + +### Create Folder Structure + +``` +User: "Set up a standard project folder structure" + +Steps (via run_code / ExecuteCode): +``` + +```csharp +string[] folders = { + "Assets/Scripts", + "Assets/Scripts/Player", + "Assets/Scripts/UI", + "Assets/Scripts/Managers", + "Assets/Scenes", + "Assets/Prefabs", + "Assets/Materials", + "Assets/Textures", + "Assets/Audio", + "Assets/Audio/SFX", + "Assets/Audio/Music", + "Assets/Animations", + "Assets/Fonts", + "Assets/Resources" +}; + +foreach (var folder in folders) +{ + if (!AssetDatabase.IsValidFolder(folder)) + { + var parts = folder.Split('/'); + var parent = parts[0]; + for (int i = 1; i < parts.Length; i++) + { + var next = parent + "/" + parts[i]; + if (!AssetDatabase.IsValidFolder(next)) + AssetDatabase.CreateFolder(parent, parts[i]); + parent = next; + } + } +} +AssetDatabase.Refresh(); +``` + +### Create Prefab from Scene Object + +```csharp +var obj = GameObject.Find("Player"); +PrefabUtility.SaveAsPrefabAsset(obj, "Assets/Prefabs/Player.prefab"); +``` + +--- + +## Debugging and Diagnostics + +### Read Console Logs + +``` +User: "Are there any errors in Unity?" + +Steps: +1. Read console logs +2. Filter by type (Error, Warning, Log) +3. Summarize findings and suggest fixes +``` + +### Clear Console + +``` +execute_menu_item("Edit/Clear Console") +``` + +### Check Project for Common Issues + +``` +User: "Check my project for problems" + +Diagnostic checklist: +1. Read console for errors/warnings +2. Check for missing script references (run_code) +3. List scenes in build settings +4. Check for unassigned serialized fields +``` + +```csharp +// Find missing scripts +var allObjects = Resources.FindObjectsOfTypeAll(); +foreach (var go in allObjects) +{ + var components = go.GetComponents(); + foreach (var c in components) + { + if (c == null) + Debug.LogWarning($"Missing script on: {go.name}"); + } +} +``` + +--- + +## Build Operations + +### Configure Build Settings + +```csharp +// Switch platform +EditorUserBuildSettings.SwitchActiveBuildTarget( + BuildTargetGroup.Standalone, + BuildTarget.StandaloneWindows64 +); + +// Add scenes to build +var scenes = new[] { + new EditorBuildSettingsScene("Assets/Scenes/MainMenu.unity", true), + new EditorBuildSettingsScene("Assets/Scenes/GameLevel.unity", true) +}; +EditorBuildSettings.scenes = scenes; +``` + +### Build the Project + +```csharp +BuildPipeline.BuildPlayer( + EditorBuildSettings.scenes, + "Builds/MyGame.exe", + BuildTarget.StandaloneWindows64, + BuildOptions.None +); +``` + +--- + +## Common Workflow Templates + +### Rapid Prototype: Simple 3D Game + +``` +User: "Help me prototype a simple ball-rolling game" + +Workflow: +1. Create scene "GameLevel" +2. Create Floor (scaled Plane at origin) +3. Create Player ball (Sphere at (0, 0.5, 0) with Rigidbody) +4. Create BallController.cs script for WASD force-based movement +5. Create collectible items (small cubes with trigger colliders) +6. Create Collectible.cs script (OnTriggerEnter → destroy + score) +7. Create ScoreManager.cs singleton +8. Create UI text for score display +9. Set up camera to follow ball +10. Add basic lighting +``` + +### Rapid Prototype: 2D Platformer + +``` +User: "Create a basic 2D platformer" + +Workflow: +1. Create 2D scene +2. Create ground tilemap or sprite +3. Create Player sprite with Rigidbody2D + BoxCollider2D +4. Create PlatformController2D.cs (horizontal movement + jump) +5. Create platforms at various heights +6. Add CameraFollow.cs for smooth camera tracking +7. Add simple death zone (trigger below platforms) +``` + +### UI Menu System + +``` +User: "Create a main menu" + +Workflow: +1. Create Canvas (Screen Space - Overlay) +2. Create Panel background +3. Create Title text (TextMeshPro) +4. Create "Start Game" button → loads game scene +5. Create "Settings" button → opens settings panel +6. Create "Quit" button → Application.Quit() +7. Create MainMenuController.cs to handle button events +8. Create SceneLoader.cs utility +``` + +--- + +## Tips for Claude Code + +1. **Always check available tools first.** Run `list available MCP tools` at the + start of a session to know what operations are supported. + +2. **Use run_code / ExecuteCode for complex operations.** When a dedicated tool + doesn't exist, write and execute C# code directly in the Unity editor. + +3. **Verify after each step.** After creating objects or scripts, read the + console and check the hierarchy to confirm success. + +4. **Handle errors gracefully.** If a tool fails, read the error message, + diagnose the issue, and try an alternative approach. + +5. **Save frequently.** Remind the user to save scenes after major changes, + or trigger save via menu item execution. + +6. **Batch operations when possible.** For creating multiple objects, write + a single C# script that creates them all rather than calling tools one by one. From eb7f944e8f696d85255c109e9f636941e8c61f3c Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 14 Apr 2026 04:58:42 +0000 Subject: [PATCH 2/2] fix: resolve markdown lint errors and security issues - Fix 51 markdownlint errors: add language tags to fenced code blocks, add blank lines around lists and fences (MD031, MD032, MD040) - Add input validation in auto_setup.sh: validate --timeout as numeric, --coplay-version as alphanumeric, check --path has a value before shift - Use pip install --user for uv installation in both auto_setup.sh and auto_setup.ps1 to avoid requiring system-level permissions - Add .gitignore for OS files, IDE configs, env/secrets, and build artifacts - Add i18n sync note to README.md contributing section https://claude.ai/code/session_01GKpTXt4npDjviK7mRzJY5A --- .gitignore | 29 +++++++++++++++++++++++++++ README.md | 10 +++++++++ SKILL.md | 25 ++++++++++++++++------- auto_setup.ps1 | 2 +- auto_setup.sh | 9 +++++++-- unity_operations.md | 49 ++++++++++++++++++++++++++------------------- 6 files changed, 93 insertions(+), 31 deletions(-) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5a0c9a3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,29 @@ +# OS files +.DS_Store +Thumbs.db +Desktop.ini + +# IDE / Editor +.vscode/ +.idea/ +*.swp +*.swo +*~ + +# Environment / Secrets +.env +.env.* +*.pem +*.key + +# Node (if running markdownlint locally) +node_modules/ + +# Python +__pycache__/ +*.pyc +.venv/ +venv/ + +# Build artifacts +*.log diff --git a/README.md b/README.md index 9c08eea..ad74d1c 100644 --- a/README.md +++ b/README.md @@ -97,6 +97,7 @@ cd "$env:USERPROFILE\.claude\skills\unity-claude-code-setup" ``` **Options:** + - `--force` / `-Force` — Remove existing MCP config before re-adding - `--timeout ` / `-Timeout ` — Custom timeout (default: 720000ms) - `--coplay-version ` / `-CoplayVersion ` — Coplay server version @@ -106,10 +107,12 @@ cd "$env:USERPROFILE\.claude\skills\unity-claude-code-setup" Once installed and connected, just talk to Claude Code naturally: **Setup:** + - *"Help me set up Claude Code with Unity"* - *"Connect my Unity project to Claude Code via MCP"* **Operations:** + - *"Create a new scene called GameLevel"* - *"Add a red cube at position (0, 2, 0)"* - *"Create a PlayerController script with WASD movement"* @@ -117,11 +120,13 @@ Once installed and connected, just talk to Claude Code naturally: - *"Check the Unity console for errors"* **Rapid prototyping:** + - *"Help me prototype a ball-rolling game"* - *"Create a basic 2D platformer"* - *"Build a main menu UI system"* **Diagnostics:** + - *"The MCP connection isn't working, help me fix it"* - *"Run diagnostics on my Unity setup"* @@ -148,6 +153,11 @@ PRs welcome! If you find a step that's outdated or want to add support for Linux or another MCP client (Cursor, Windsurf, etc.), feel free to open an issue or submit a pull request. +> **Note on i18n:** The translations under `i18n/` currently reflect the +> original setup-guide version of this skill. They have not yet been updated +> to cover the new auto-setup scripts, operations guide, or rapid prototyping +> workflows. Contributions to update them are especially welcome. + ## License MIT — see [LICENSE](LICENSE). diff --git a/SKILL.md b/SKILL.md index 4b68f74..2e5202c 100644 --- a/SKILL.md +++ b/SKILL.md @@ -39,6 +39,7 @@ bash auto_setup.sh --path unity # Force Unity Official MCP ``` **Options:** + - `--force` / `-Force` — Remove existing config before re-adding - `--timeout ` / `-Timeout ` — Custom timeout (default: 720000) @@ -120,6 +121,7 @@ Verify the target MCP server (unity-mcp or coplay-mcp) is listed. ### Step 2 — Test MCP connection Try a simple tool call: + - **Coplay:** `list_editors` — should return open Unity instances - **Unity Official:** `Unity_ReadConsole` — should return console messages @@ -168,7 +170,8 @@ Read `unity_operations.md` for the complete tool reference and code templates. ### Scene Management **Create a new scene:** -``` + +```text 1. execute_menu_item("File/New Scene") 2. Save via run_code: EditorSceneManager.SaveScene( @@ -176,32 +179,37 @@ Read `unity_operations.md` for the complete tool reference and code templates. ``` **Get scene contents:** -``` + +```text get_scene_hierarchy → returns full object tree ``` **Save scene:** -``` + +```text execute_menu_item("File/Save") ``` ### GameObject Operations **Create primitives (Cube, Sphere, Capsule, Plane, Cylinder):** -``` + +```text create_primitive("Cube", name="MyCube") set_component_property("MyCube", "Transform", "position", {x:0, y:1, z:0}) ``` **Create hierarchy:** -``` + +```text 1. Create parent: create_gameobject("Player") 2. Create children and parent them under Player 3. Set transforms for each child ``` **Add components:** -``` + +```text add_component("Player", "Rigidbody") add_component("Player", "CharacterController") set_component_property("Player", "Rigidbody", "mass", 2.0) @@ -232,6 +240,7 @@ public class PlayerController : MonoBehaviour { ``` Common script patterns (see `unity_operations.md` for full templates): + - **PlayerController** — WASD movement with CharacterController - **GameManager** — Singleton pattern with DontDestroyOnLoad - **HealthBarUI** — Slider-based UI with color gradient @@ -278,12 +287,14 @@ run_code(@" ### Debugging **Read console messages:** -``` + +```text get_console_logs or Unity_ReadConsole → Summarize errors and warnings, suggest fixes ``` **Find missing scripts:** + ```csharp run_code(@" foreach (var go in Resources.FindObjectsOfTypeAll()) { diff --git a/auto_setup.ps1 b/auto_setup.ps1 index b17beda..b6b51b3 100644 --- a/auto_setup.ps1 +++ b/auto_setup.ps1 @@ -169,7 +169,7 @@ function Setup-Coplay { } catch { Write-Info "uvx not found. Installing uv..." try { - pip install uv 2>$null + pip install --user uv 2>$null Get-Command uvx -ErrorAction Stop | Out-Null Write-Pass "uvx installed successfully" } catch { diff --git a/auto_setup.sh b/auto_setup.sh index 340b348..a07c97c 100644 --- a/auto_setup.sh +++ b/auto_setup.sh @@ -41,12 +41,17 @@ usage() { while [[ $# -gt 0 ]]; do case "$1" in --path) + if [[ $# -lt 2 ]]; then fail "--path requires a value (coplay or unity)"; exit 1; fi MCP_PATH="$2"; shift 2 ;; --auto) MCP_PATH="auto"; shift ;; --timeout) + if [[ $# -lt 2 ]]; then fail "--timeout requires a value"; exit 1; fi + if ! [[ "$2" =~ ^[0-9]+$ ]]; then fail "--timeout must be a positive integer (got: $2)"; exit 1; fi MCP_TIMEOUT="$2"; shift 2 ;; --coplay-version) + if [[ $# -lt 2 ]]; then fail "--coplay-version requires a value"; exit 1; fi + if ! [[ "$2" =~ ^[a-zA-Z0-9._-]+$ ]]; then fail "--coplay-version contains invalid characters (got: $2)"; exit 1; fi COPLAY_VERSION="$2"; shift 2 ;; --force) FORCE=true; shift ;; @@ -200,9 +205,9 @@ setup_coplay() { else info "uvx not found. Installing uv..." if command -v pip3 &>/dev/null; then - pip3 install uv 2>/dev/null + pip3 install --user uv 2>/dev/null elif command -v pip &>/dev/null; then - pip install uv 2>/dev/null + pip install --user uv 2>/dev/null else fail "pip not found. Cannot install uv automatically." echo " Install manually: pip install uv" diff --git a/unity_operations.md b/unity_operations.md index 6afddeb..f3d2ef6 100644 --- a/unity_operations.md +++ b/unity_operations.md @@ -38,7 +38,7 @@ after the MCP connection is established. ### Create a New Scene -``` +```text User: "Create a new scene called MainMenu" Steps: @@ -48,7 +48,8 @@ Steps: ``` **Coplay MCP approach:** -``` + +```text execute_menu_item("File/New Scene") run_code(" UnityEditor.SceneManagement.EditorSceneManager.SaveScene( @@ -59,7 +60,8 @@ run_code(" ``` **Unity Official MCP approach:** -``` + +```text Unity_ExecuteMenuItem("File/New Scene") Unity_ExecuteCode(" EditorSceneManager.SaveScene( @@ -71,7 +73,7 @@ Unity_ExecuteCode(" ### List All Objects in Scene -``` +```text User: "What's in the current scene?" Steps: @@ -81,7 +83,7 @@ Steps: ### Save Current Scene -``` +```text execute_menu_item("File/Save") or Ctrl+S equivalent ``` @@ -91,7 +93,7 @@ execute_menu_item("File/Save") or Ctrl+S equivalent ### Create Basic Objects -``` +```text User: "Create a red cube at (0, 2, 0)" Steps: @@ -102,7 +104,8 @@ Steps: ``` **Coplay MCP approach:** -``` + +```text create_primitive("Cube", name="RedCube") set_component_property("RedCube", "Transform", "position", {"x":0, "y":2, "z":0}) run_code(" @@ -116,7 +119,7 @@ run_code(" ### Create Complex Hierarchies -``` +```text User: "Create a player character with a body, head, and two arms" Steps: @@ -130,7 +133,7 @@ Steps: ### Add Components -``` +```text User: "Add a Rigidbody to the Player" Steps: @@ -145,7 +148,7 @@ Steps: ### Create a MonoBehaviour Script -``` +```text User: "Create a PlayerController script that handles WASD movement" Steps: @@ -155,6 +158,7 @@ Steps: ``` **Template — PlayerController.cs:** + ```csharp using UnityEngine; @@ -188,11 +192,12 @@ public class PlayerController : MonoBehaviour ### Create a Singleton Manager -``` +```text User: "Create a GameManager singleton" ``` **Template — GameManager.cs:** + ```csharp using UnityEngine; @@ -218,11 +223,12 @@ public class GameManager : MonoBehaviour ### Create a UI Controller -``` +```text User: "Create a health bar UI script" ``` **Template — HealthBarUI.cs:** + ```csharp using UnityEngine; using UnityEngine.UI; @@ -249,7 +255,7 @@ public class HealthBarUI : MonoBehaviour ### Create and Assign Materials -``` +```text User: "Make the floor a wooden texture" Approach (via run_code / ExecuteCode): @@ -259,6 +265,7 @@ Approach (via run_code / ExecuteCode): ``` **Code pattern:** + ```csharp var floor = GameObject.Find("Floor"); var renderer = floor.GetComponent(); @@ -269,7 +276,7 @@ renderer.material = mat; ### Setup Basic Lighting -``` +```text User: "Set up a basic 3-point lighting" Steps: @@ -291,7 +298,7 @@ RenderSettings.skybox = Resources.Load("Skybox/DefaultSkybox"); ### Create Folder Structure -``` +```text User: "Set up a standard project folder structure" Steps (via run_code / ExecuteCode): @@ -346,7 +353,7 @@ PrefabUtility.SaveAsPrefabAsset(obj, "Assets/Prefabs/Player.prefab"); ### Read Console Logs -``` +```text User: "Are there any errors in Unity?" Steps: @@ -357,13 +364,13 @@ Steps: ### Clear Console -``` +```text execute_menu_item("Edit/Clear Console") ``` ### Check Project for Common Issues -``` +```text User: "Check my project for problems" Diagnostic checklist: @@ -425,7 +432,7 @@ BuildPipeline.BuildPlayer( ### Rapid Prototype: Simple 3D Game -``` +```text User: "Help me prototype a simple ball-rolling game" Workflow: @@ -443,7 +450,7 @@ Workflow: ### Rapid Prototype: 2D Platformer -``` +```text User: "Create a basic 2D platformer" Workflow: @@ -458,7 +465,7 @@ Workflow: ### UI Menu System -``` +```text User: "Create a main menu" Workflow: