I’ve been sort of hacking away at trying to get C# 9’s source generator functionality working in Unity. I know that Unity doesn’t support C#9, however source generators have been made back-compatible with older language versions and frameworks.
So I’ve compiled a DLL containing a working source generator, imported the DLL and tagged as a RoslynAnalyzer, and do get proper intellisense in the code editor where it picks up the generated class. So the generator is sort of working (with no errors on DLL import or anything).
However, though the compiler isn’t finding any errors at edit time in the IDE, when I open unity I get “The name ‘HelloWorldGenerated’ does not exist in the current context”.
I’m a bit stumped as to what I should try next. I’m starting to think that something is going on with the way RoslynAnalyzers are tagged that the Generator is being put in some different compilation pipeline in Unity and the code it emits is being done after the normal process of script compilation.
I’ve also found that Analyzers generally don’t work unless there is a .asmdef file next to the scripts it affects, which I suspect is bumping up the script in the compilation order or something to be used before the DLLs are referenced? Not sure.
I know this isn’t a stated use-case for Roslyn analyzers that Unity supports, but I think getting this to work would be a huge boon for the development process globally. Would love to know what other people have tried and if anyone has any inklings about ways to get this working!
I am also interested in this. I wish we had a supported way to write/use/package source generators (especially since the DOTS team is supposedly experimenting with them for codegen already).
This looks super interesting, I’ve never heard of/used this before. I’m worried about it producing a lot of project bloat though if used - do you have experience with it? And what are the chances Unity just bumps the Roslyn version for 2020.2?
Just want to throw it out there you actually can use source generators with Unity if you build your code as a managed dll. It is something I am doing currently and it has worked wonderfully.
It really depends on the Unity version you are using. Unity 2020 iirc was kinda weird and inconsistent with SourceGenerators, but moving to later versions and following the https://docs.unity3d.com/Manual/roslyn-analyzers.html docs works perfectly.