IPreprocessBuild (editor script): How to stop a build that fails validation?

For example, if x, y or z test values are accidentally left ON, cancel the build?

2 Likes

Throwing an exception from OnPreprocessBuild (or OnPreprocessBuildWithReport) should do the trick

2 Likes

Doesn’t work

Can confirm throwing an exception inside OnPreprocessBuild stops the build process:

throw new System.OperationCanceledException("Build was canceled by the user.");

With Unity 2018.3.9, IPreprocessBuildWithReport does not prevent the build from starting. The error is thrown after the build is completed or aborted manually by user.
I managed to prevent the building with the following:

using UnityEditor;
using UnityEditor.Build.Reporting;
using UnityEngine;

[InitializeOnLoad]
public class NewMonoBehaviour
{
    static NewMonoBehaviour()
    {
        Debug.Log("Called");
        BuildPlayerWindow.RegisterBuildPlayerHandler(test);
    }

    public static void test(BuildPlayerOptions obj)
    {
        throw new BuildPlayerWindow.BuildMethodException();//this prevents editor to start the building process
    }

When all your tests succeeded, you can start the build process with BuildPipeline.BuildPlayer(obj); in the test method.

7 Likes

this does not work for me

This solution worked for me on Unity 2019.2

FYI, there should be a stong emphasis on the fact that you have to throw either a BuildPlayerWindow.BuildMethodException or (preferred way) a BuildFailedException.

BuildPlayerWindow.BuildMethodException is not so good.
The documentation clearly states that it should be used to indicate abort or failure in the callbacks registered via BuildPlayerWindow.RegisterBuildPlayerHandler and BuildPlayerWindow.RegisterGetBuildPlayerOptionsHandler.

8 Likes

In Unity 2019.4+ throwing a normal “Exception” in OnPreprocessBuild() will no longer stop the build, but throwing a “BuildFailedException” will.

3 Likes

It’s worked
for me