新建一个Roslyn项目

image-20240724224353032

在CodeAnalyzer方案中新建一个分析器脚本,具体代码直接让GPT写,这玩意没必要特意学

image-20240724224618742

比如说我让GPT给我写了一个禁止使用Debug.Log的分析器

using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;

[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class DebugLogAnalyzer : DiagnosticAnalyzer
{
    public const string DiagnosticId = "DebugLogAnalyzer";
    private static readonly LocalizableString Title = "禁止使用 Debug.Log";
    private static readonly LocalizableString MessageFormat = "禁止使用 Debug.Log 方法";
    private static readonly LocalizableString Description = "在代码中不允许使用 Debug.Log 方法。";
    private const string Category = "Usage";

    private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(
        DiagnosticId, Title, MessageFormat, Category, 
        DiagnosticSeverity.Warning, isEnabledByDefault: true, 
        description: Description);

    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics 
        => ImmutableArray.Create(Rule);

    public override void Initialize(AnalysisContext context)
    {
        context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
        context.EnableConcurrentExecution();
        context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.InvocationExpression);
    }

    private void AnalyzeNode(SyntaxNodeAnalysisContext context)
    {
        var invocationExpr = (InvocationExpressionSyntax)context.Node;

        // 检查调用的表达式是否是 Debug.Log
        if (invocationExpr.Expression is MemberAccessExpressionSyntax memberAccess 
            && memberAccess.Name.ToString() == "Log"
            && context.SemanticModel.GetSymbolInfo(memberAccess.Expression).Symbol is INamedTypeSymbol typeSymbol
            && typeSymbol.ToString() == "UnityEngine.Debug")
        {
            var diagnostic = Diagnostic.Create(Rule, invocationExpr.GetLocation());
            context.ReportDiagnostic(diagnostic);
        }
    }
}

然后编译,生成解决方案,找到生成的DLL丢进Unity任意目录

image-20240724224847442

对DLL进行如下设置

image-20240724225417778

添加一个RoslynAnalyzer的Label标签

image-20240724225405381

编译一下项目,也可能需要重启unity,然后就会生效了

image-20240724225532841

只会分析该DLL所属程序集,和引用这个程序集的程序集