You can use code analyzers to inspect your code for errors, rule violations, and coding style issues. As with source generators, you can use existing analyzers or create your own.
To create a Roslyn analyzer in your IDE and then apply it for use in your Unity project:
In your IDE, create a C# class library project that targets .NET Standard 2.0 and name the project ExampleAnalyzer.
Install the Microsoft.CodeAnalysis.Csharp NuGet package for the project. Your analyzer must use Microsoft.CodeAnalysis.Csharp 4.3 to work with Unity.
In your IDE project, create a new C# file and add the following code:
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace ExampleAnalyzer
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class DebugLogAnalyzer : DiagnosticAnalyzer
{
public const string DiagnosticId = "EX0001";
private static readonly LocalizableString Title =
"Avoid using Debug.Log";
private static readonly LocalizableString MessageFormat =
"Debug.Log call detected - consider removing it before shipping";
private static readonly LocalizableString Description =
"Debug.Log calls can impact performance and clutter the console in production builds.";
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(AnalyzeInvocation, SyntaxKind.InvocationExpression);
}
private static void AnalyzeInvocation(SyntaxNodeAnalysisContext context)
{
var invocation = (InvocationExpressionSyntax)context.Node;
if (!(invocation.Expression is MemberAccessExpressionSyntax memberAccess))
return;
// Match calls where the method name is "Log"
if (memberAccess.Name.Identifier.Text != "Log")
return;
// Verify the symbol belongs to UnityEngine.Debug
var symbolInfo = context.SemanticModel.GetSymbolInfo(memberAccess);
if (!(symbolInfo.Symbol is IMethodSymbol methodSymbol))
return;
var containingType = methodSymbol.ContainingType;
if (containingType?.ToDisplayString() != "UnityEngine.Debug")
return;
var diagnostic = Diagnostic.Create(Rule, memberAccess.GetLocation());
context.ReportDiagnostic(diagnostic);
}
}
}
Build your analyzer with a release build configuration.
In your analyzer’s project folder, find the bin/Release/netstandard2.0/ExampleAnalyzer.dll file.
Copy this file into your Unity project, inside the Assets folder.
Inside the Asset Browser, click on the .dll file to open the Plugin Inspector window.
Under Select platforms for plugin, uncheck Any Platform.
Under Include Platforms, uncheck Editor and Standalone and any other checked platforms.
Under Asset Labels, click on the label icon to open the Asset labels sub-menu.
Create and assign a new label called RoslynAnalyzer. To do this, type RoslynAnalyzer in the text input fieldA field that allows the user to input a Text string More info
See in Glossary of the Asset labels sub-menu and press Enter. This label must match exactly and is case sensitive. Once created, the label appears in the Asset labels sub-menu from then on. You can click on the name of the label in the menu to assign it to other analyzers.
To test the analyzer is working, create a new MonoBehaviour script in the Editor with the following code:
using UnityEngine;
public class TestScript : MonoBehaviour
{
void Start()
{
Debug.Log("Hello world"); // Should trigger EX0001 warning
}
}
After Unity recompiles scriptsA piece of code that allows you to create your own Components, trigger game events, modify Component properties over time and respond to user input in any way you like. More info
See in Glossary, the following warning appears in the Console:
TestScript.cs(8,9): warning EX0001: Debug.Log call detected - consider removing it before shipping
For more information on creating Roslyn analyzers, refer to Tutorial: Write your first analyzer and code fix in the Microsoft documentation.
To view information such as the total execution time of your analyzers and source generators or the relative execution times of each analyzer or source generator, go to Edit > Preferences (macOS: Unity > Settings) > Editor Diagnostics > Core and enable EnableDomainReloadTimings. When enabled, the information is displayed in the console window.