How to add Roslyn code-analyzers to Unity project? (for Unity versions below 2020)

Viewed 1243

When I install Roslyn code-analyzer as NuGet-package for a project (say Assembly-CSharp) of solution of my Unity-project, 2 things happen:

  • package is installed to Packages folder at Unity-project root
  • and lines like <Analyzer Include="packages\SomeAnalyzer.1.2.3\analyzers\dotnet\cs\SomeAnalyzer.dll" /> are added to the .csproj file (in our case Assembly-CSharp.csproj)

The problem is - Unity regenerates .csproj file (f.e. when you add or remove .cs files or when you close and reopen Unity editor). Regeneration of .csproj erases added lines, mentioned above. And analyzers stop working.

Looks like for Unity 2020 the problem is solved. But my project is on Unity 2019 & could not be updated to 2020 now. So I my question is: Is it possible to add code analyzer to Unity-project and make it work for Unity versions below 2020?

2 Answers

Ok, I've found some solutions:

#1 Code with smell, but it works (but most likely one of the next two solution is better for you):

(found it here) We accept that Unity erases lines about installed package from .csproj file. But we use a Unity hook AssetPostprocessor.OnGeneratedCSProjectFiles to "manually" rewrite .csproj returning those lines.

#2 Much more elegant way (I chose it)

(found it here) We just put the Directory.Build.props file near our .sln & put (manually, but once) in it lines, which Unity removes from .csproj. That's all.

#Note: if you want to analyzer work not for all projects, you could use Condition for Property group.

#3 I didn't check it, but may be it will become the best solution for you

(found it here) We should add Assets/csc.rsp file which references analyzer dlls & ruleset in such way:

-a:"full_or_relative_path_to_UnityEngineAnalyzer.dll"
-ruleset:"full_or_relative_path_to_rules.ruleset"

It may works only with Rider (IDE), 'cos requirements stated as:

Applies to Unity 2019.2+ with Rider package 1.1.3+

Been looking at the feature of analysers for unity, on a 2019.4 version, the csproj files do get generated correctly without any csc.rsp files if I follow the following rules from unity (from the link you posted) :

  • Move the three .dll files into the Assets folder (or any folder nested in the Assets folder) in your Unity project.
  • In the Editor, select the .dll file. In the Plugin Inspector, under Select platforms for plugin, disable Any Platform. Under Include platforms, disable Editor and Standalone platforms.
  • Then, give all of the DLLs a new label called RoslynAnalyzer.

But now I do not get the warnings I was looking for in the console of Unity. The warnings are there on a 2020 version though. Are you able to see the warnings from the new analysers in a 2019 version of unity ?

Related