Custom Build step before compilation

Now that Unity has upgraded .NET support to 4.6, I am looking to update my package dependency process which I setup using this great guide: Unity and NuGet +

While I’m at it, I thought I would update the process to make it easier to use. Since Unity doesn’t respect NuGet conventions which download .dll’s for each .NET runtime which a package supports, I can’t simply tell NuGet to install to Assets/Packages because (for example) NewtonSoft.Json downloads multiple .NET versions like this:

Unity (understandably) complains that an assembly `Newtonsoft.Json’ with the same identity has already been imported. I thought that a simple solution would be to write a custom build step which simply loops through all dependencies in the default NuGet storage location (./packages), and copies the relevant folder to ./Assets/Packages. This way we don’t need to store NuGet dependencies in source control, and both NuGet and Unity stick with the default conventions.

Unfortunately it seems that Unity cannot execute custom build steps if there is a compilation error. I have tried creating a class which implements the build hook interfaces:

public class NuGetBuildProcessor : IPreprocessBuild, IActiveBuildTargetChanged, IProcessScene
    public int callbackOrder => int.MinValue;
    public void OnProcessScene(UnityEngine.SceneManagement.Scene scene)

    public void OnActiveBuildTargetChanged(BuildTarget previousTarget, BuildTarget newTarget)

    public void OnPreprocessBuild(BuildTarget target, string path)

But it seems that none of these callbacks execute if there is a compilation error. The only exception to this rule is if this class is created before the compilation errors are introduced in which case I guess it enters the Unity cache until Unity is closed. This doesn’t help me because it means that a team-mate checking out new changes for the first time needs to remove all the code with compilation errors in order for the script to run.

The other thing I tried was to add a MenuItem (a less desirable but acceptable solution) so that the user can manually trigger the NuGet restore+copy. It seems that custom menu items also fail to load though if Unity starts up with a compilation error.

Is there another build hook which I’m missing? Is this a bug? To my mind a ‘build’ represents every step required to turn text-based code files into an executable. With this in mind, I feel that something called ‘PreprocessBuild’ would be a pre-compilation step, followed by compilation, assembly and finally post-processing (and I imagine many steps in between).

It seems that custom menu items also fail to load though if Unity starts up with a compilation error.

That’s because Unity compiles the assembly, then loads it to read classes.

So… Put your helper utilities/menu items in their own asset bndle?

The bundle should load even if your main project fails to compile