Files
2026-03-13 12:34:01 +07:00
..
2026-03-13 12:34:01 +07:00
2026-03-13 12:34:01 +07:00
2026-03-13 12:34:01 +07:00
2026-03-13 12:34:01 +07:00
2026-03-13 12:34:01 +07:00

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ị)

  1. Build analyzer project:
cd UnityEditorOnlyAnalyzer
dotnet build -c Release
  1. Thêm analyzer vào Unity project bằng cách chỉnh sửa .csproj files:
<ItemGroup>
  <Analyzer Include="$(SolutionDir)UnityEditorOnlyAnalyzer\bin\Release\netstandard2.0\UnityEditorOnlyAnalyzer.dll" />
</ItemGroup>

Cách 2: Sử dụng như NuGet Package

  1. Tạo NuGet package:
dotnet pack -c Release
  1. Thêm vào packages.config hoặ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_EDITOR nhưng được gọi từ code không có directive này
  • Một class được định nghĩa trong #if UNITY_EDITOR như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_EDITOR như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