AgentSkillsCN

unity-editor-operations

在操作Unity编辑器时使用此技能。支持通过JSON命令创建/修改游戏对象、变换、材质、场景、预制件、灯光、摄像机、UI和地形。必须先调用以获取正确的命令格式,然后再执行。

SKILL.md
--- frontmatter
name: unity-editor-operations
description: "Use this skill when operating Unity Editor. Supports creating/modifying GameObjects, transforms, materials, scenes, prefabs, lights, cameras, UI, and terrain via JSON commands. MUST invoke first to get correct command format before executing."

Unity Editor Operations Skill

Overview

This skill enables Unity Editor operations through JSON commands. Commands are sent via send_message.py to Unity Command Server and executed immediately with results returned.

Architecture:

code
Claude Code (this side - Agent)
  ↓ JSON command
send_message.py (WebSocket client)
  ↓ ws://127.0.0.1:8766
Unity Command Server (simple executor)
  ↓
CommandExecutor
  ↓
Unity Editor Operations
  ↓ JSON result
send_message.py
  ↓
Claude Code (receives result)

Quick Start

1. Open Unity Command Server

In Unity Editor: Tools > ClaudeAgent > Unity Command Server

2. Send Command

bash
python .claude/skills/unity-editor-operations/send_message.py '{"operation":"create_primitive","params":{"type":"sphere","name":"MySphere","color":"red"}}'

3. Check Result

code
✓ Connected to ws://127.0.0.1:8766/
📤 Sending: {"operation":"create_primitive",...}
⏳ Waiting for response (timeout: 10s)...

✓ Command executed successfully
   Time: 2025-11-25 18:00:00

send_message.py Usage

Located at: .claude/skills/unity-editor-operations/send_message.py

bash
python send_message.py '<json_command>'

Features:

  • WebSocket connection to Unity Command Server
  • 10 second timeout
  • JSON result parsing and display
  • Exit code: 0 (success) / 1 (failure)

Response Format:

json
{
  "success": true,
  "result": { ... },
  "timestamp": "2025-11-25 12:00:00"
}

JSON Command Format

json
{
  "operation": "operation_name",
  "params": {
    "param1": "value1",
    "param2": "value2"
  }
}

Common Parameters

Space Parameters

Several operations support position_space, rotation_space, and scale_space parameters:

ParameterValuesDefault
position_space"local" / "world""world" if no parent, "local" if parent specified
rotation_space"local" / "world""world" if no parent, "local" if parent specified
scale_space"local" / "world""world" if no parent, "local" if parent specified

Applies to: create_primitive, create_empty, create_line, instantiate_prefab, create_terrain

Result messages show which space was used: Created sphere: MySphere (position: world, scale: local)

Supported Operations (60 total)

Looking up operation details: Use Grep "### operation_name" File.md -A 25 to retrieve only the specific operation section instead of reading the entire file. This reduces token consumption.

GameObject Operations

OperationDescription
create_primitiveCreate sphere, cube, etc. ※VGM: markers only
create_emptyCreate empty GameObject
delete_gameobjectDelete by path/name
set_activeSet active state
tagGet/set tag (unified)
create_tagCreate new tag in project
delete_tagDelete custom tag from project
find_gameobjectFind and return info
set_nameRename
set_parentSet parent-child relationship
duplicate_gameobjectDuplicate
look_atOrient towards target
create_lineCreate line between two points

Transform Operations

OperationDescription
transformGet/set position, rotation, scale (unified)

Component Operations

OperationDescription
add_componentAdd component
remove_componentRemove component
get_componentGet component info
set_component_propertySet property value
get_componentsList all components
set_object_referenceSet GameObject/Component reference

Material Operations

OperationDescription
materialGet/set material properties (unified)
create_materialCreate new material

Scene Operations

OperationDescription
open_sceneOpen scene
save_sceneSave scene
create_sceneCreate new scene
get_scene_hierarchyGet hierarchy structure
get_active_sceneGet active scene info

Asset Operations

OperationDescription
create_assetCreate text asset
delete_assetDelete asset
get_assetGet asset info
import_assetRe-import asset
refresh_assetsRefresh AssetDatabase
copy_assetCopy asset
import_packageImport .unitypackage file
list_assetsList assets in folder

Prefab Operations

OperationDescription
create_prefabCreate from GameObject
instantiate_prefabInstantiate into scene
open_prefabOpen in edit mode
save_prefabSave prefab

Debugging Operations

Light Operations

OperationDescription
create_lightCreate light
lightGet/set light properties (unified)

Camera Operations

OperationDescription
create_cameraCreate camera
cameraGet/set camera properties (unified)

Screenshot Operations

OperationDescription
capture_scene_viewCapture scene screenshot

UI Operations

Editor Operations

OperationDescription
execute_menu_itemExecute menu item
get_editor_stateGet editor state
get_selectionGet selected objects
set_selectionSelect object
playmodePlay mode control (play/stop/pause/resume)

Animator Operations

Terrain Operations

OperationDescription
create_terrainCreate terrain
add_terrain_layerAdd texture layer
terrain_heightGet/set/paint terrain height (unified)
terrain_textureFill/paint terrain texture (unified)

ProBuilder Operations

Visual Guide Modeling Operations

OperationDescription
create_fittedCreate geometry fitted to vertex positions ※VGM: geometry

Batch Operations (Meta-Operation)

Execute multiple commands in a single request for better performance. This is not a new Unity operation, but a wrapper to execute existing 59 operations in batch.

Batch Format

json
{
  "operation": "batch",
  "params": {
    "commands": [
      {"operation": "create_primitive", "params": {"type": "sphere", "name": "Ball", "color": "red"}},
      {"operation": "transform", "params": {"path": "Ball", "position": [0, 2, 0]}},
      {"operation": "create_light", "params": {"type": "point", "color": "yellow"}}
    ]
  }
}

Batch Features

FeatureDescription
Max commands20 per batch
Execution orderSequential (array order)
Error handlingStops on first error, remaining cancelled
UndoAll commands in one Undo group (single Ctrl+Z)
Nested batchNot allowed

Batch Response

json
{
  "success": true,
  "results": [
    {"index": 0, "success": true, "result": "Created sphere: Ball"},
    {"index": 1, "success": true, "result": "Set Ball position to (0,2,0)"},
    {"index": 2, "success": true, "result": "Created point light"}
  ],
  "summary": {
    "total": 3,
    "succeeded": 3,
    "failed": 0,
    "cancelled": 0
  }
}

Batch Error Response

When a command fails, remaining commands are cancelled:

json
{
  "success": false,
  "results": [
    {"index": 0, "success": true, "result": "Created sphere: Ball"},
    {"index": 1, "success": false, "error": "GameObject not found: MissingObj"},
    {"index": 2, "success": false, "error": "Cancelled: previous command failed"}
  ],
  "summary": {
    "total": 3,
    "succeeded": 1,
    "failed": 1,
    "cancelled": 1
  }
}

When to Use Batch

  • Creating multiple related objects
  • Setting up a scene with multiple elements
  • Any operation requiring 3+ sequential commands
  • Performance-critical operations (reduces window activation overhead)

Best Practices

Script Generation: Local File Creation

For C# scripts, create files locally using Claude Code's Write tool instead of WebSocket commands.

This approach is recommended because:

  • Faster execution: No WebSocket round-trip required
  • Easier debugging: Scripts can be read/modified directly
  • No JSON escaping: Avoid complex string escaping issues
  • Full IDE support: Syntax highlighting and IntelliSense during creation

Workflow:

  1. Create the .cs file locally using Write tool at Assets/YourFolder/YourScript.cs
  2. Call refresh_assets to make Unity detect the new file:
    bash
    python send_message.py '{"operation":"refresh_assets","params":{}}'
    
  3. Unity will automatically compile the script
  4. Use logs with filter: "errors" to check for compilation errors if needed

Example script structure:

csharp
using UnityEngine;

public class MyBehavior : MonoBehaviour
{
    void Update()
    {
        // Your code here
    }
}

Always Verify Scene State

Before and after operations, use get_scene_hierarchy to confirm the current state:

bash
# Check scene before operations
python send_message.py '{"operation":"get_scene_hierarchy","params":{"max_depth":2}}'

# Perform operations...

# Verify changes after operations
python send_message.py '{"operation":"get_scene_hierarchy","params":{}}'

Why this matters:

  • Same-named objects may exist at different hierarchy levels
  • Batch delete may miss objects (e.g., root Cube0 vs Cubes/Cube0)
  • Confirms all intended changes were applied

Recommended Workflow

  1. Get scene state - Understand current hierarchy before changes
  2. Plan operations - Identify exact paths for objects to modify
  3. Execute commands - Use batch for multiple related operations
  4. Verify results - Check scene hierarchy to confirm changes
  5. Clean up - Delete any unintended objects

Examples

bash
# Create object
python send_message.py '{"operation":"create_primitive","params":{"type":"sphere","name":"Ball","color":"red","position":[0,1,0]}}'

# Query scene
python send_message.py '{"operation":"get_scene_hierarchy","params":{"max_depth":3}}'

# Modify object
python send_message.py '{"operation":"transform","params":{"path":"Ball","position":[5,0,0],"rotation":[0,45,0]}}'

# Batch operations (max 20 commands)
python send_message.py '{"operation":"batch","params":{"commands":[
  {"operation":"create_primitive","params":{"type":"cube","name":"Floor","scale":[10,0.1,10]}},
  {"operation":"create_primitive","params":{"type":"sphere","name":"Ball","color":"red","position":[0,1,0]}}
]}}'

Server Information

ItemValue
URLws://127.0.0.1:8766
ProtocolWebSocket + JSON
Timeout10 seconds
Unity WindowTools > ClaudeAgent > Unity Command Server

Troubleshooting

Connection Refused

  1. Open Unity Editor
  2. Open: Tools > ClaudeAgent > Unity Command Server
  3. Verify status is "Running" (green)

Timeout (10s)

  • Check Unity Console for errors
  • Command may be taking too long
  • Restart Command Server

Command Failed

  • Check operation name (case-sensitive)
  • Verify parameter names
  • See category-specific .md files for details
  • Errors are returned as-is (no fallback)

Unknown Parameter Warning

If you use an invalid or misspelled parameter name, the command will still execute but include a warning:

code
Created sphere: MySphere
[WARNING] Unknown parameters ignored: positon, colr

This helps identify typos (e.g., positon instead of position) without failing the command. The warning appears after the result message.

Connection Lost After refresh_assets

The refresh_assets operation may cause a temporary WebSocket disconnection:

Symptoms:

  • Commands immediately after refresh_assets fail with connection errors
  • Server status shows "Reconnecting..."

Cause: AssetDatabase.Refresh() can trigger a domain reload when new scripts are detected, which restarts the Unity Command Server.

Solution:

  1. Wait a moment (1-2 seconds) after refresh_assets before sending the next command
  2. If connection fails, retry the command once
  3. The server automatically restarts after domain reload - no manual restart needed

Note: This behavior only occurs when refresh_assets detects new or modified scripts that require recompilation. Asset-only changes (textures, prefabs, etc.) do not trigger domain reload.