关于 unity-editor-tooling
面向 Unity 开发者的编辑器扩展与工具开发参考,涵盖自定义界面、构建自动化、测试及包开发。内容也涉及版本控制和程序集配置。
主要功能
- 01自定义 Inspector 与属性绘制器
- 02创建 EditorWindow 工具
- 03编写脚本化导入器
- 04自动化构建与 CI/CD
- 05Unity Test Framework 测试
- 06配置程序集与 UPM 包
适用场景
- 01为组件定制编辑界面
- 02创建独立编辑器工具
- 03在 CI 中构建 Unity 项目
- 04编写 Edit Mode 和 Play Mode 测试
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ josiahsiegel/ claude-plugin-marketplace --skill unity-editor-tooling安装后在 Claude Code 中输入/unity-editor-tooling确认已加载。
详细介绍
Unity 编辑器脚本编写与工具开发
概述
Unity 编辑器扩展、构建自动化、测试、版本控制配置和软件包开发参考。涵盖自定义检查器、编辑器窗口、构建管线脚本、CI/CD 和 Unity Test Framework。
自定义检查器
基础自定义编辑器
#if UNITY_EDITOR
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(EnemySpawner))]
public class EnemySpawnerEditor : Editor
{
SerializedProperty spawnPoints;
SerializedProperty enemyPrefab;
SerializedProperty spawnInterval;
void OnEnable()
{
spawnPoints = serializedObject.FindProperty("_spawnPoints");
enemyPrefab = serializedObject.FindProperty("_enemyPrefab");
spawnInterval = serializedObject.FindProperty("_spawnInterval");
}
public override void OnInspectorGUI()
{
serializedObject.Update();
EditorGUILayout.PropertyField(enemyPrefab);
EditorGUILayout.Slider(spawnInterval, 0.1f, 10f, new GUIContent("Spawn Interval"));
EditorGUILayout.Space();
EditorGUILayout.LabelField("Spawn Points", EditorStyles.boldLabel);
EditorGUILayout.PropertyField(spawnPoints, true);
if (GUILayout.Button("Add Spawn Point at Origin"))
{
spawnPoints.InsertArrayElementAtIndex(spawnPoints.arraySize);
var newElement = spawnPoints.GetArrayElementAtIndex(spawnPoints.arraySize - 1);
newElement.vector3Value = Vector3.zero;
}
serializedObject.ApplyModifiedProperties();
}
void OnSceneGUI()
{
var spawner = (EnemySpawner)target;
// Draw handles in scene view for each spawn point
for (int i = 0; i < spawner.SpawnPointCount; i++)
{
Vector3 point = spawner.GetSpawnPoint(i);
Vector3 newPoint = Handles.PositionHandle(point, Quaternion.identity);
if (point != newPoint)
{
Undo.RecordObject(spawner, "Move Spawn Point");
spawner.SetSpawnPoint(i, newPoint);
}
}
}
}
#endif
关键规则:
- 始终将编辑器代码放在
#if UNITY_EDITOR中,或放入Editor/文件夹 - 使用
SerializedProperty支持撤销/重做和多对象编辑 - 在修改前调用
serializedObject.Update(),修改后调用ApplyModifiedProperties() - 直接修改前调用
Undo.RecordObject()
PropertyDrawer
[CustomPropertyDrawer(typeof(MinMaxRange))]
public class MinMaxRangeDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
EditorGUI.BeginProperty(position, label, property);
var min = property.FindPropertyRelative("min");
var max = property.FindPropertyRelative("max");
float minVal = min.floatValue;
float maxVal = max.floatValue;
position = EditorGUI.PrefixLabel(position, label);
EditorGUI.MinMaxSlider(position, ref minVal, ref maxVal, 0f, 100f);
min.floatValue = minVal;
max.floatValue = maxVal;
EditorGUI.EndProperty();
}
}
使用 PropertyDrawer 实现可复用的字段级自定义。使用 CustomEditors 实现组件级自定义。
EditorWindow
public class LevelEditorWindow : EditorWindow
{
[MenuItem("Tools/Level Editor")]
static void ShowWindow() => GetWindow<LevelEditorWindow>("Level Editor");
Vector2 scrollPos;
string searchFilter = "";
void OnGUI()
{
EditorGUILayout.BeginHorizontal(EditorStyles.toolbar);
searchFilter = EditorGUILayout.TextField(searchFilter, EditorStyles.toolbarSearchField);
if (GUILayout.Button("Refresh", EditorStyles.toolbarButton, GUILayout.Width(60)))
RefreshData();
EditorGUILayout.EndHorizontal();
scrollPos = EditorGUILayout.BeginScrollView(scrollPos);
// Draw content
EditorGUILayout.EndScrollView();
}
void OnSelectionChange() => Repaint(); // React to selection changes
}
使用 EditorWindow 创建独立工具。使用 [MenuItem] 集成到菜单栏。重写 OnSelectionChange、OnHierarchyChange、OnProjectChange,以响应变化并更新。
ScriptedImporter
[ScriptedImporter(1, "leveldata")]
public class LevelDataImporter : ScriptedImporter
{
public override void OnImportAsset(AssetImportContext ctx)
{
string json = File.ReadAllText(ctx.assetPath);
var levelData = ScriptableObject.CreateInstance<LevelData>();
JsonUtility.FromJsonOverwrite(json, levelData);
ctx.AddObjectToAsset("main", levelData);
ctx.SetMainObject(levelData);
}
}
注册自定义文件扩展名。源文件更改时,Unity 会自动重新导入。
构建管线
构建脚本
public static class BuildScript
{
[MenuItem("Build/Build Windows")]
public static void BuildWindows()
{
var options = new BuildPlayerOptions
{
scenes = EditorBuildSettings.scenes
.Where(s => s.enabled)
.Select(s => s.path).ToArray(),
locationPathName = "Builds/Windows/Game.exe",
target = BuildTarget.StandaloneWindows64,
options = BuildOptions.None
};
var report = BuildPipeline.BuildPlayer(options);
if (report.summary.result != BuildResult.Succeeded)
throw new Exception($"Build failed: {report.summary.totalErrors} errors");
}
}
使用 GameCI(GitHub Actions)实现 CI/CD
name: Unity Build
on:
push:
branches: [main]
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
targetPlatform: [StandaloneWindows64, StandaloneLinux64, WebGL]
steps:
- uses: actions/checkout@v4
with:
lfs: true
- uses: game-ci/unity-builder@v4
env:
UNITY_LICENSE: ${{ secrets.UNITY_LICENSE }}
UNITY_EMAIL: ${{ secrets.UNITY_EMAIL }}
UNITY_PASSWORD: ${{ secrets.UNITY_PASSWORD }}
with:
targetPlatform: ${{ matrix.targetPlatform }}
buildMethod: BuildScript.Build${{ matrix.targetPlatform }}
- uses: actions/upload-artifact@v4
with:
name: build-${{ matrix.targetPlatform }}
path: build/${{ matrix.targetPlatform }}
先使用 game-ci/unity-activate 激活 Unity 许可证。如果 CI 运行器容量不足,可改用 Unity Build Automation(Cloud Build)。
程序集定义
Project/
├── Scripts/
│ ├── Core/ Core.asmdef (no references)
│ ├── Gameplay/ Gameplay.asmdef (references: Core)
│ ├── UI/ UI.asmdef (references: Core, Gameplay)
│ ├── Networking/ Networking.asmdef (references: Core)
│ ├── Editor/ Editor.asmdef (references: Core; Editor-only platform)
│ └── Tests/
│ ├── EditMode/ Tests.EditMode.asmdef (references: Core; Test assemblies)
│ └── PlayMode/ Tests.PlayMode.asmdef (references: Core, Gameplay)
**优点:**增量编译(仅重新编译有更改的程序集)、强制执行依赖边界、可测试性的必要条件。
规则:
- 将仅限 Editor 的程序集设置为仅面向 Editor 平台
- 测试程序集必须引用
UnityEngine.TestRunner和UnityEditor.TestRunner - 使用 Assembly Definition References 实现跨程序集访问
Unity Test Framework
Edit Mode 测试
[TestFixture]
public class InventoryTests
{
[Test]
public void AddItem_IncreasesCount()
{
var inventory = new Inventory(maxSlots: 10);
inventory.Add(new Item("Sword", 1));
Assert.AreEqual(1, inventory.Count);
}
[Test]
public void AddItem_WhenFull_ReturnsFalse()
{
var inventory = new Inventory(maxSlots: 1);
inventory.Add(new Item("Sword", 1));
Assert.IsFalse(inventory.Add(new Item("Shield", 1)));
}
}
Play Mode 测试
[UnityTest]
public IEnumerator Player_TakesDamage_HealthDecreases()
{
var player = new GameObject().AddComponent<PlayerHealth>();
player.Initialize(100);
player.TakeDamage(30);
yield return null; // Wait one frame
Assert.AreEqual(70, player.CurrentHealth);
}
通过 Window > General > Test Runner 运行测试。Edit Mode 测试会立即运行。Play Mode 测试会进入播放模式,可用于测试 MonoBehaviour 逻辑、协程和物理效果。
版本控制
Unity .gitignore(必要条目)
/[Ll]ibrary/
/[Tt]emp/
/[Oo]bj/
/[Bb]uild/
/[Bb]uilds/
/[Ll]ogs/
/[Uu]ser[Ss]ettings/
/[Mm]emoryCaptures/
/[Rr]ecordings/
*.csproj
*.sln
*.suo
*.user
*.pidb
*.booproj
*.unityproj
版本控制的项目设置
- Edit > Project Settings > Editor > Asset Serialization:Force Text
- Edit > Project Settings > Editor > Version Control Mode:Visible Meta Files
- 使用 Unity Smart Merge:配置
.gitattributes,添加*.unity merge=unityyamlmerge - 安装 UnityYAMLMerge(随 Unity 一同提供),并将 git 配置为使用它
自定义软件包(UPM)
com.company.my-package/
├── package.json
├── Runtime/
│ ├── com.company.my-package.asmdef
│ └── MyScript.cs
├── Editor/
│ ├── com.company.my-package.editor.asmdef
│ └── MyEditorScript.cs
├── Tests/
│ ├── Runtime/
│ └── Editor/
├── Documentation~/
├── CHANGELOG.md
└── README.md
通过 manifest.json 安装本地软件包:"com.company.my-package": "file:../../Packages/my-package",或通过 git URL 安装。
其他资源
参考文件
references/editor-recipes.md-- 高级编辑器模式:Gizmos、Handles、SceneView 覆盖层、自定义菜单、资源后处理器、构建钩子(IPreprocessBuildWithReport)、序列化回调、Terrain 和 ProBuilder 脚本编写、多场景编辑工作流