Generate code before build in project with compiler errors

I generate some code in my project (e.g. constants for UXML names).
Because this is generated code, I do not add it to VCS. Thus, initially some code is missing on a fresh clone of the project, which leads to compiler errors.

I have a IPreprocessBuildWithReport script that triggers the generation of the required code.
Sadly, this does not work because the build is cancled due to compiler errors before the IPreprocessBuildWithReport is triggered.

Questions:

  • Is there a build hook to create assets (including code) although the initial project setup may contain compiler errors?
  • Or do I have to generate the code before opening Unity? This would be unfortunate, because in this case, code generation cannot be done from within Unity’s C#.

Unity 2022.2.4f1

InitializeOnLoadMethod does not work as well.

The package resolution is triggered when opening the project.
Maybe a hook for this could be used to generate code before the build starts?

I think InitializeOnLoad might work. But it does not for me. Maybe I have to declare it in an asmdef that is loaded before the asmdef with missing code?

Question is: how does Unity load and run the code?

  • Is it done assembly for assembly such that I could create an early assembly to generate code?
  • Or is Unity loading everything upfront and then executing nothing because of compiler errors?

Maybe I have to declare it in an asmdef that is loaded before the asmdef with missing code

Yes, this did the trick.

How does Unity load and run the code?

Indeed, It is done assembly for assembly such that I could create an early assembly to generate code

TIP: Make sure to write code files only if the content changed. Otherwise you may end up in an endless loop of recompilation / reloading packages.

1 Like

Yes, this did the trick.

Except in batch mode (from command line). Unity quits prematurely with Aborting batchmode due to failure: Scripts have compiler errors
Looks like Unity loads the project differently in batch mode.

Thus, this does not work with our continuous integration (CI).

Please let me know how to properly generate code in Unity from C#.
Only solution I see at the moment is to add all generated files to VCS, which is an unlucky workaround.

It is… but for the codegen I do in my Datasacks package, I just chose to do this and move on.

My add new asset workflow is thus:

  • add new Datasack (a ScriptableObject)
  • name it appropriately, move it where you want
  • select it and press CODE GEN in the inspector
  • commit ALL new files and changes (including the codegen file)

Now go write your code to use your asset.

I favor lots of small commits so changing codegen stuff is happy to me. I don’t put random changing data such as “generation date” in my codegen code, generally speaking. I just don’t care. I want a checked out repo to build without fail 100% of the time. That is far more important to me than some extra commit noise.