Search Unity

  1. Unity Asset Manager is now available in public beta. Try it out now and join the conversation here in the forums.
    Dismiss Notice
  2. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  3. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Question Support Roslyn analyzers in Unity projects

Discussion in '2020.2 Beta' started by Peter77, Jul 8, 2020.

  1. EternalClickbait

    EternalClickbait

    Joined:
    May 5, 2019
    Posts:
    22
    About the fix, which Unity version will it be available in?
     
  2. JohnPontoco

    JohnPontoco

    Joined:
    Dec 23, 2013
    Posts:
    292
    Additionally, can you update us on when the Temp folder error will be solved, and which versions? Currently, as far as I know, this is blocking anyone using Roslyn Analyzers in a large project.
     
  3. Trond_Tactile

    Trond_Tactile

    Joined:
    May 25, 2016
    Posts:
    17
    Sorry for being completely noob here. But I have a really hard time following this documentation: https://docs.unity3d.com/2020.2/Documentation/Manual/roslyn-analyzers.html

    How do I install NuGet packages in Unity? I had to do so through Rider, and then copy the DLLs manually. But in doing do, all the DLLs dependencies are missing. I ended up having to import https://github.com/mwahnish/Unity-Roslyn to get all the dependencies. Is this what you guys have been doing?

    Also, I cannot get Rider to use the analyzers. It says that its unable to load the requested types.


    Can somebody create a step-by-step guide in how to get Roslyn Analyzers working?
     
    neonblitzer likes this.
  4. AlphaDreams

    AlphaDreams

    Joined:
    Jan 21, 2015
    Posts:
    30
    I will try to do explain each step really quickly, because I agree the documentation may be improved.

    For the dependency error that you got, see the end of this message.

    Adding a Roslyn Analyzer

    Step 1
    : Get the
    .dll
    file(s) for the analyzer you want to add to your Unity project.

    1.1. Open your project in your IDE
    1.2. Install the NuGet package of your analyzer in your project
    1.3. At the root of your project, open the folder "Packages". The NuGet package must be installed in it.
    1.4. Search for the
    .dll
    files for your analyzer in the hierarchy. Some analyzers may use multiple files, so be careful to really select all the useful ones.

    Step 2 : Import the
    .dll
    files to Unity

    2.1. Copy your analyzer's
    .dll
    files into your Assets folder (or any subfolder)
    2.2. Select them in the Project windows in Unity and open them in the inspector
    2.3. Under "Select platforms for plugin", disable everything like this :

    upload_2021-5-11_11-57-27.png

    2.4. Set the label for all the files to "RoslynAnalyzer" (at the bottom of the inspector, the little blue icon). You way need to create a new label (just type it and enter). Be careful to make no mistake in the name of the label!

    upload_2021-5-11_11-59-6.png

    Step 3 : Reimport your scripts

    The code analysis may not run right away. In order to trigger it, you may want to reimport your scripts.

    To do this, right-click on your folder that stores all the scripts in your game, and click on "Reimport".

    You can also "Reimport all" if you don't have one specific folder for your scripts.

    Troubleshoots

    I got an error that say that a folder is missing in the "Temp" folder

    For the moment, you can simply create the missing folder by hand, and the error will disappear. I'm not sure if it's really a permanent fix, but at the moment it seems to work for me.

    There are errors in the console that say that some dependencies are missing in my dlls

    Not sure about this one, but I had this error when I had a typo in the label name "RoslynAnalyzer". You way need to double-check it.
     
    sandolkakos likes this.
  5. Trond_Tactile

    Trond_Tactile

    Joined:
    May 25, 2016
    Posts:
    17
    AlphaDreams thank you very much!

    I encountered an issue when installing the suggested analyzer from the documentation, where no dependencies were pulled in. This meant that I only ended up with the 3 DLLs mentioned in the documentation, which did not work.

    However, if I manually installed the Microsoft.CodeAnalysis.CSharp NuGet package as well, it compiled just fine. That does however result in 40 DLLs imported into Unity. Is that really correct?
     
    neonblitzer likes this.
  6. AlphaDreams

    AlphaDreams

    Joined:
    Jan 21, 2015
    Posts:
    30
    I'll be honest, I did not test it with the analyzers specified in the documentation.
    But even with another analyzer - StyleCop in my case - when I added the dll files in my project there were errors in the console that told me that some dependencies were missing, especially
    Microsoft.CodeAnalysis
    and two or three other packages.

    Like I said in my previous answer, Unity told me that these dependencies were missing only because I had a typo in the label name "RoslynAnalyzer". I fixed it, and now everything runs smoothly, and I didn't had to add any other dlls in the project other than the two first.

    I'm clearly not sure about this, but it's possible that Unity resolve these dependencies automatically when you give your dll files the correct label?

    Also, don't forget that if you try something and nothing change, you can :

    - Reimport you script folder (Right clic in the project window on your folder, then "Reimport")
    - Reimport all (Right clic anywhere in the project window, then "Reimport all", but it will take time, especially if you're working on a large project)
    - Regenerate the project files ("Edit" > "Preferences" > "External Tools" > "Regenerate Project Files")

    It may trigger something that will resolve your problem.

    And if someone with more insight about this than me can answer how all this works, it can be great! :)
     
  7. HaraldNielsen

    HaraldNielsen

    Unity Technologies

    Joined:
    Jun 8, 2016
    Posts:
    142
    I dont know about this error. Do you have a public issue tracker for it?
     
  8. HaraldNielsen

    HaraldNielsen

    Unity Technologies

    Joined:
    Jun 8, 2016
    Posts:
    142
    I will mention this to the documentation team and they will hopefully make it more friendly :)
     
  9. JohnPontoco

    JohnPontoco

    Joined:
    Dec 23, 2013
    Posts:
    292
    It's the issue most of the first page of this thread is talking about. It doesn't seem like it was ever addressed or resolved.
     
  10. mbaker

    mbaker

    Joined:
    Jan 9, 2013
    Posts:
    52
    Thank you all for the information shared so far. Getting the analyser to work in VS2019 was the last piece of the puzzle for me.

    For those that are having trouble copying DLLs over from NuGet or want an easier way to maintain their NuGet packages there is NuGetForUnity (https://github.com/GlitchEnzo/NuGetForUnity). I've pulled in both ErrorProne .NET analyzers using NuGetForUnity and it works well.

    Just make sure to commit the DLLs to your version control, otherwise you'll have to manually repeat the DLL import on each new checkout.
     
  11. DB_Smooth

    DB_Smooth

    Joined:
    Dec 1, 2019
    Posts:
    4
    Nice, another half assed non functioning feature that only exists to aggravate the user base.
     
    bdovaz likes this.
  12. HaraldNielsen

    HaraldNielsen

    Unity Technologies

    Joined:
    Jun 8, 2016
    Posts:
    142
    We are using Analyzers internally as well, with Assembly Definitions and continue to improve the workflow as much as possible, including documentation so you guys not have to guess what to do or rely on forum posts.

    The bad thing in this workflow, IMO, is that we lack the basic tooling that makes working with Analyzers easy, compared to normal C# development.
    We are trying to improve that workflow as well, but sadly a lot of legwork needs to be done to get there.
     
    marcospgp likes this.
  13. nowsprinting

    nowsprinting

    Joined:
    Nov 3, 2014
    Posts:
    18
    At least in Unity 2020.3.12f1, the analyzer placed under Packages seems to be working.
    However, I cannot find any mention of it in the release notes.

    What is Unity's position on the analyzer under Packages folder?

    I would also like to see support for .editorconfig file for severity settings.
     
  14. nowsprinting

    nowsprinting

    Joined:
    Nov 3, 2014
    Posts:
    18
    I'm posting a PR for Roslyn analyzer support but it's not merged.
    Please use it if you are interested.
    https://github.com/GlitchEnzo/NuGetForUnity/pull/393
     
    mbaker likes this.
  15. BIICameronReuschel

    BIICameronReuschel

    Joined:
    May 7, 2021
    Posts:
    5
    @HaraldNielsen I'd like to write custom analyzers/generators in my Unity project. It's a large project that would benefit massively from code generation. What's the best way to go about that? I'd like the generator code to have access to the sources of other selected assemblies, so that project-wide refactorings don't break the source generators.

    I could obviously maintain a completely separate project, build it, include the dll in the unity project, label it as RoslynAnalyzer, etc. But that's a massive overhead for small changes.

    I could also not use Roslyn Generators, and instead write an editor script that triggers on compilation and writes a source file before triggering another compilation. But that would require two compilations each time, which would be a constant annoying overhead in a large project.

    Are there any better ways to get code generation for source files in Unity? Can I just write my analyzer/generator in a folder with an `.asmdef` and maybe include the dll as `-analyzer:` as compiler arg or something?
     
    FICHEKK likes this.
  16. WeirdBeardDev

    WeirdBeardDev

    Joined:
    Feb 16, 2013
    Posts:
    14
    Did you ever find a way to ignore specific assemblies?
     
  17. HaraldNielsen

    HaraldNielsen

    Unity Technologies

    Joined:
    Jun 8, 2016
    Posts:
    142
    Hi sorry for the late reply, somehow missed this :)
    For source generators we had to upgrade some things to support this feature, as of 2021.2 you can use Source Generators to generate code.

    For workflow, that is sadly the only way currently to include/compile a source generator.
     
    DrViJ likes this.
  18. HaraldNielsen

    HaraldNielsen

    Unity Technologies

    Joined:
    Jun 8, 2016
    Posts:
    142
    AlphaDreams and WeirdBeardDev like this.
  19. sandolkakos

    sandolkakos

    Joined:
    Jun 3, 2009
    Posts:
    285
    Hey @HaraldNielsen, I just started to look into Roslyn Analyzers and after adding some DLLs and making them work correctly, I'm now wondering if there is any way to write my analyzers in the same source project of my game?

    I would make use of AssemblyDefinitions to encapsulate and organize everything and maybe also create a Package out of it.
     
    JesOb likes this.
  20. HaraldNielsen

    HaraldNielsen

    Unity Technologies

    Joined:
    Jun 8, 2016
    Posts:
    142
    @sandolkakos atm we dont support that yet, but it will come as we have issue internally as well.
     
    Laicasaane and sandolkakos like this.
  21. sandolkakos

    sandolkakos

    Joined:
    Jun 3, 2009
    Posts:
    285
    Thanks for sharing that info @HaraldNielsen
    I'm looking forward to using it like that.
     
    HaraldNielsen likes this.
  22. Laicasaane

    Laicasaane

    Joined:
    Apr 15, 2015
    Posts:
    378
    Our company has just run into this problem recently when we were trying to nail down a good enough process of building Unity packages for internal use. Supporting analyzers and source generators inside a Unity project will ease our work greatly as we don't have much manpower to maintain and develop different kinds of projects. Atm we have to resort to some tricks to make codegen developable inside a Unity package (even though we have to tolerate harmless errors constantly logged in the Console view).
     
    HaraldNielsen and sandolkakos like this.
  23. BIICameronReuschel

    BIICameronReuschel

    Joined:
    May 7, 2021
    Posts:
    5
    @HaraldNielsen I am sorry to bother you again, but source generators do not work for me.

    We have upgraded to Unity 2021.2.2f1. I have started a new analyzer/generator project as a separate project, compiled it, moved the DLL into the assets folder and given it the `RoslynAnalyzer` asset tag.

    The default analyzer works fine (in Rider), but the generator does not seem to be triggered. No logs are forwarded, no diagnostics displayed. The IDE picks up the generated code, but Unity neither sees it nor compiles it. The generator itself has unit tests that work, and the emitted output looks fine.

    Could you please provide a tutorial or maybe even an example of how to get a custom Source Generator to work properly within Unity? This is a blocking issue for some features, as alternatives to code generation are a lot less elegant.
     
  24. HaraldNielsen

    HaraldNielsen

    Unity Technologies

    Joined:
    Jun 8, 2016
    Posts:
    142
    We have updated the docs recently about Analyzers and Source Generators
    https://docs.unity3d.com/2022.1/Documentation/Manual/roslyn-analyzers.html

    But I see we dont write what you need to reference when you want to create one.
    Since all are signed assemblies, you need to reference the correct version with the Roslyn version you are targeting.
    For that I would recommend using what we ship with the editor, located:
    `{EditorInstallPath}\Data\DotNetSdkRoslyn`

    What you want to reference are:
    Microsoft.CodeAnalysis.CSharp
    Microsoft.CodeAnalysis.Analyzers

    I will make sure the documentaion gets this information added. Let me know if that fixes your issue alone.
    Also Roslyn should write out if it for some version reason cant load the assemblies, was anything reported in the Editor log about your source generator?
     
  25. Randhall

    Randhall

    Joined:
    Feb 21, 2013
    Posts:
    17
    @HaraldNielsen

    Is there any way to package a Roslyn Generator in a unity package (UPM package not *.unitypackage file)?

    My generator works when it is in the Assets folder but when I try to create a package with the dlls that are needed for it to work, and put them in the packages folder or import them using package manager the generator doesn't work.

    Is there something extra that needs to be done in order for generators to work when distributed through UPM packages?

    If it helps here's the generator repository. It's a small open source ECS generator library.
    I am trying to distribute it as a package (on top of the *.unitypackage file) as it's a feature that has been requested by some of my library users.

    It would make their repositories cleaner and updating the library easier.

    I am attaching a zip of the package folder along with it's meta files to make it easier to identify if I am doing something wrong.
     

    Attached Files:

  26. HaraldNielsen

    HaraldNielsen

    Unity Technologies

    Joined:
    Jun 8, 2016
    Posts:
    142
    Hi, yes that should work just fine. Can you take a empty project with some simple code you expected getting source genned with your package as local, and push it some where, or create a bug. Then I can take a look locally to see whats going on
     
  27. HaraldNielsen

    HaraldNielsen

    Unity Technologies

    Joined:
    Jun 8, 2016
    Posts:
    142
    Also want to add that we use Source Generators internally, but I think they all use the Assembly Definition scope, so the source generator from the package is only used if its referencing the AssemblyDefinition
     
  28. Randhall

    Randhall

    Joined:
    Feb 21, 2013
    Posts:
    17
    You are right it does work when I did it in a clean project.
    I must have had some library folder garbage or something else must have been happening for it not to work.
    Thank you so much for pinging me to do the bare minimum test.

    If anyone would still be interested here is the repo with 2 ways of using the generator one from internal asset folder and another one with the package approach.
     
    sandolkakos and HaraldNielsen like this.
  29. BIICameronReuschel

    BIICameronReuschel

    Joined:
    May 7, 2021
    Posts:
    5
    I just had time to get back to this. I can't find the `Microsoft.CodeAnalysis.Analyzers` dll in neither 2021.2 nor 2022.1:

    upload_2022-1-20_3-13-53.png

    Path to 2022.1: `C:\Program Files\Unity\2022.1.0b4\Editor\Data\DotNetSdkRoslyn` <- this seems to correspond to what you wrote.

    I assume that referencing works like in a managed plugin (https://docs.unity3d.com/Manual/UsingDLL.html)?

    Alternatively, can I just include the right versions of those plugins in NuGet? And if yes, could you please tell me the version for the `Microsoft.CodeAnalysis.Analyzers` dependency? The others are on 3.9.0. Thanks!

    @HaraldNielsen
     
  30. BIICameronReuschel

    BIICameronReuschel

    Joined:
    May 7, 2021
    Posts:
    5
    Because the edit post feature does not work: A small example project for a Source Generator that runs with Unity 2021.1.2.2f1 would be immensely appreciated and would solve my problems for the foreseeable future.
     
    neonblitzer likes this.
  31. BIICameronReuschel

    BIICameronReuschel

    Joined:
    May 7, 2021
    Posts:
    5
    Alright, I got it I think:

    1. Create a netstandard2.0 class library project
    2. Explicitly add Microsoft.CodeAnalysis.CSharp version 3.9.0 (the same Unity uses) from NuGet
    3. Don't have any other fancy dependencies in there like I had with the original analyzer template that I tried to use
    4. Follow Unity's import steps (RoslynAnalyzer asset label, etc)
    5. Restart Unity and the IDE twice or so until it works
     
  32. Deleted User

    Deleted User

    Guest

    Hi, I'm enjoying using analyzers in my project, and it's nice being able to set some warnings as errors. However, I was wanting to fail a test or build if there were specific errors thrown by the analyzers (for CI purposes). Is there a way to do that?
     
  33. DrViJ

    DrViJ

    Joined:
    Feb 9, 2013
    Posts:
    164
    Hi! Can anybody explain please, if it is correct that I can't import Microsoft.CodeAnalysis and then write a SourceGenerator with attribute [Generator] in Unity, but instead of this I must have a precompiled dll with all my SourceGenerators there? I see that generators with attribute work when they are inside dll, and they do not work in classes outside it. Is that correct? The example in documentation has a SourceGenerator inside DLL too.
     
  34. brunocoimbra

    brunocoimbra

    Joined:
    Sep 2, 2015
    Posts:
    679
    If you add SourceGenerator label to the analyzer DLL, it will also emit the warnings and errors in the Unity console, thus failing a build if there is any error.

    However, rulesets / editorconfig seems to be ignored by Unity in this case, so you will need to change the default severity in the analyzer code to make Unity pick it correctly.
     
  35. brunocoimbra

    brunocoimbra

    Joined:
    Sep 2, 2015
    Posts:
    679
    Only as DLL for now.
     
    DrViJ likes this.
  36. Tooster

    Tooster

    Joined:
    Jan 30, 2019
    Posts:
    12
    Hi, I would like to take a look at that repo but it's gone. Do you still have it?
     
  37. Randhall

    Randhall

    Joined:
    Feb 21, 2013
    Posts:
    17
    Hi Tooster unfortunately it has been removed some time ago. Are you having problems some problems with setting up Roslyn Generators in your project ?
    I don't have the old project as it evolved into a bit bigger library.
    If you want you can go here and pull the package from the repo or use the UPM approach described in the readme to see how it is set up. It should work in both approaches and if it doesn't you can ping me on the discord channel that's linked in there as well and I can try and help after work.
     
  38. Tooster

    Tooster

    Joined:
    Jan 30, 2019
    Posts:
    12
    Yeah, I want to write my own source generator inside my (embedded?) package (in the root Packages directory, meant to be exported later as an official package), but nothing I try seems to work. Unfortunately the official docs were greatly unhelpful in setting it up. I am not even sure on which stage I make some mistakes - on the source generator project level, on the unity asset level, the custom package level, maybe on an assembly level or maybe something completely else. Thanks for reply, I'll try to contact you soon.
     
    neonblitzer likes this.
  39. Laicasaane

    Laicasaane

    Joined:
    Apr 15, 2015
    Posts:
    378
    I'm currently using Unity 2022.3 and it does support SG in UPM packages. My setup is based on Unity.Entities package.
     
  40. Tooster

    Tooster

    Joined:
    Jan 30, 2019
    Posts:
    12
    Ok, I made it work, here are the steps:
    1. First of all, ensure that the package has correct structure :p
    2. create another project for source generator. Make sure it targets netstandard2.0. Add Microsoft.CodeAnalysis.CSharp in ver 3.9.0 (it is compatible with unity, contrary with docs)
    3. Make sure that your source generator outputs code WITH CORRECT NAMESPACE
    4. put the dll in any folder of the package. I put it in the folder with another, sub assembly definition file. Source generator
    5. Apply RoslynAnalyzer and SourceGenerator tags to dll. disable any platform and others, like the official guide says.

    It is important to understand 2 things:
    - source generator applies to all assemblies in subdirectories it is put in
    - generated sources must have correct namespaces

    When the time comes I'll link my project somewhere here
     
    neonblitzer likes this.
  41. marcospgp

    marcospgp

    Joined:
    Jun 11, 2018
    Posts:
    197
    I tried setting up analyzers in Unity but couldn't get around errors of this kind:

    These are the analyzers I was trying to set up:

    upload_2023-10-3_15-52-7.png
     
    sandolkakos and pahe like this.
  42. marcospgp

    marcospgp

    Joined:
    Jun 11, 2018
    Posts:
    197
    2024 update:

    Unity includes its custom analyzers in its generated `.csproj`, the path for which varies depending on which editor you select in the settings:

    upload_2024-5-4_20-9-36.png

    upload_2024-5-4_20-9-27.png

    The warnings do not seem to show up in the Unity console however, just in the VSCode editor.

    Update: I was able to get other analyzer DLLs to show up in the same place in the `.csproj` file by following the instructions in the documentation: https://docs.unity3d.com/2022.3/Documentation/Manual/roslyn-analyzers.html

    But as before, while the warnings do show up in VSCode (using the C# dev kit extension), they do not show up in the Unity editor's console.
     
    Last edited: May 4, 2024
    sandolkakos likes this.
  43. HaraldNielsen

    HaraldNielsen

    Unity Technologies

    Joined:
    Jun 8, 2016
    Posts:
    142
    @marcospgp - Some of the IDE packages only add these analyzers to the generated csproj's but not included in the build in Unity. So thats why you are not seeing the warnings in Unity.
    While adding the Analyzer's as described in the documentation adds them both to the compilation trough Unity, and in the generated csproj's
     
  44. marcospgp

    marcospgp

    Joined:
    Jun 11, 2018
    Posts:
    197
    > While adding the Analyzer's as described in the documentation adds them both to the compilation trough Unity, and in the generated csproj's

    That's what I did @HaraldNielsen , and as mentioned I only see the warnings in VSCode, not in the Unity editor console

    I disabled the DLLs for all platforms and added the RoslynAnalyzer label as described in the docs

    (I tested this in MacOS which could play a role)
     
  45. HaraldNielsen

    HaraldNielsen

    Unity Technologies

    Joined:
    Jun 8, 2016
    Posts:
    142
    @marcospgp - oh I misunderstood "I was able to get other analyzer DLLs to show up in the same place in the `.csproj` file by following the instructions in the documentation".
    So when adding the label, it works in the IDE only, not in Unity?

    In `\Library\Bee\*EDbg.dag.json` are the graph that our buildsystem executes, in there you should be able to find the compilation of the DLL ("csc" invocation) you expect including your analyzer. Copying that command and trying to execute it locally could maybe help understand whats going on.
    That said, what you see in the IDE of analyzers, should be a representation of what we use to compile with as well, as the data is from the same place, so it should be included.