Question: Do anyone know any method to get a callback right before compilation in the Unity Editor?
I want to refresh an automatically generated CS file right before recompilation so it gets compiled properly.
I know about the CompilationPipeline-compilationStarted but the problem with this is that it gets called too late. After generating my file I need to call the AssetDatabase.Refresh() in order to update the file.
And that triggers another compilation, which means an endless loop of Compile…
Obviously, I can mitigate it with a static variable and follow that the second time around I shouldn’t update my file, but this isn’t ideal, compiling will get worse and worse as the code grows, obviously, compiling twice is a big blow, especially in 2021.x.
Any other ideas?
That sounds like a great use case for C# Source Generators, maybe one day we’ll be able to use them in Unity?
You could try to wait for any script file to change using AssetPostprocessor.OnPostprocessAllAssets but that could also be already too late, depending on when Unity determines the scripts/assemblies to recompile.
Another option, that I have no experience with, could be Compilation.AssemblyBuilder, i.e. keep your generated source file outside of Unity and use AssemblyBuilder to generate a managed assembly. There’s also no guarantee that the updated assembly will be picked up by the current compile but maybe the chances are better than with source files.
1 Like
Yeah. But unfortunately I can’t wait until then. 
This is a good idea, I will check this out.
Unfortunately this isn’t going to work for me either. I have an editor-time database with a bunch of data and on compile I generate constants and static accessors for them. It’s like the InputSystem’s ‘generate file’ option, I just want to do it without hitting a button. Although maybe I’ll be forced to have a ‘Save’ button so I can generate the code during saving.