Write Better Unity Code With Rosyln C# Analyzers

Jordan Cassady
2 min readAug 11, 2021

Adding static analysis to a Unity project’s C# codebase can help improve software by identifying code that’s high quality (“good”) from code that’s low quality (“bad”). To do this, we can use Roslyn-based analyzers for C# inside of the Unity editor, and manage them with rulesets.

Rulesets can be obtained with NuGet, the .NET package manager. The Unity manual page on static code analyzers uses ErrorProne’s .NET Core Analyzers package, which is what I’ll be using in this post.

Follow along with me as I go through the steps required to setup static analysis in any Unity project. By the time we’re done, you’ll know how to use NuGet to install rulesets inside of the Unity editor. You’ll also write a test script to display a warning originating from the ErrorProne.NET package.

  1. Install NuGetForUnity by visiting the releases page, and download the latest .unitypackage file. Install NuGet into your Unity project by dragging it into your Assets folder:

2. Using NuGet in Unity, install the ErrorProne.NET.CoreAnalyzer package:

3. Follow the .dll instructions described on the Unity docs page by updating ErrorProne.NET.Core, ErrorProne.Net.CoreAnalyzers and RuntimeContracts, located under Assets/Packages in the Unity editor:

Also remember to give the three .dll files a new asset label titled “RoslynAnalyzer”, otherwise static analysis will not work.

4. Add the RethrowError.cs test script from the Unity docs page and ensure warnings EPC12 and ERP021 are displayed on the Unity console:

If you don’t see the above warnings, relaunch the Unity editor and check the console again.

With static analysis configured in your project, any future code changes that violate rules belonging to the ErrorProne ruleset will also be displayed on the Unity console until the issue has been resolved, or an exception has been added to the project’s Default.ruleset file. Check out the ruleset section of the Unity docs page for more details.

Have you used static analysis alongside Unity before? Let me know in the comments.

--

--