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

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: (Unity - Manual: Roslyn analyzers and ruleset files). 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?

I’ve found a solution.

@KislunA Do you try to do the second solution?, did it work for you? I try to do the second solution but I have not been able to obtain it.

Blockquote
#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.