2.1 KiB
2.1 KiB
Unity Editor Only Usage Analyzer
Roslyn Analyzer để phát hiện việc sử dụng code được wrap trong #if UNITY_EDITOR từ code không có directive tương ứng, có thể gây lỗi build.
Cài đặt
Cách 1: Build và thêm vào .csproj (Khuyến nghị)
- Build analyzer project:
cd UnityEditorOnlyAnalyzer
dotnet build -c Release
- Thêm analyzer vào Unity project bằng cách chỉnh sửa
.csprojfiles:
<ItemGroup>
<Analyzer Include="$(SolutionDir)UnityEditorOnlyAnalyzer\bin\Release\netstandard2.0\UnityEditorOnlyAnalyzer.dll" />
</ItemGroup>
Cách 2: Sử dụng như NuGet Package
- Tạo NuGet package:
dotnet pack -c Release
- Thêm vào
packages.confighoặc sử dụng PackageReference trong .csproj
Cách hoạt động
Analyzer sẽ cảnh báo khi:
- Một method được định nghĩa trong
#if UNITY_EDITORnhưng được gọi từ code không có directive này - Một class được định nghĩa trong
#if UNITY_EDITORnhưng được khởi tạo từ code không có directive này - Một property/field được định nghĩa trong
#if UNITY_EDITORnhưng được truy cập từ code không có directive này
Ví dụ
❌ Code sẽ bị cảnh báo:
#if UNITY_EDITOR
public void EditorOnlyMethod() { }
#endif
public void RegularMethod()
{
EditorOnlyMethod(); // ⚠️ Cảnh báo: EditorOnlyMethod chỉ có trong UNITY_EDITOR
}
✅ Code đúng:
#if UNITY_EDITOR
public void EditorOnlyMethod() { }
#endif
#if UNITY_EDITOR
public void RegularMethod()
{
EditorOnlyMethod(); // ✅ OK: Cả hai đều trong UNITY_EDITOR
}
#endif
Diagnostic ID
- ID:
UNITY_EDITOR_ONLY_USAGE - Severity: Warning
- Category: Unity
Tùy chỉnh
Bạn có thể disable warning này trong .editorconfig:
[*.cs]
dotnet_diagnostic.UNITY_EDITOR_ONLY_USAGE.severity = none
Hoặc trong code:
#pragma warning disable UNITY_EDITOR_ONLY_USAGE
// Your code here
#pragma warning restore UNITY_EDITOR_ONLY_USAGE