首页 > 解决方案 > 如何通过 Unity 编辑器脚本强制构建过程失败?

问题描述

如果不满足某些验证条件,我想强制构建过程失败。

我试过使用IPreprocessBuildWithReport没有成功:

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

public class BuildProcessor : IPreprocessBuildWithReport
{
    public int callbackOrder => 0;

    public void OnPreprocessBuild(BuildReport report)
    {
        // Attempt 1
        // Does not compile because the 'BuildSummary.result' is read only
        report.summary.result = BuildResult.Failed;

        // Attempt 2
        // Causes a log in the Unity editor, but the build still succeeds
        throw new BuildFailedException("Forced fail");
    }
}

有没有办法以编程方式强制构建过程失败?

我正在使用 Unity 2018.3.8f1。

标签: unity3d

解决方案


从 2019.2.14f1 开始,停止构建的正确方法是抛出BuildFailedException.

其他异常类型不会中断构建。
派生的异常类型不会中断构建。
记录错误肯定不会中断构建。

这是 Unity 在PostProcessPlayer中处理异常的方式:

try
{
    postprocessor.PostProcess(args, out props);
}
catch (System.Exception e)
{
    // Rethrow exceptions during build postprocessing as BuildFailedException, so we don't pretend the build was fine.
    throw new UnityEditor.Build.BuildFailedException(e);
}


只是为了清楚起见,这不会停止构建。:

// This is not precisely a BuildFailedException. So the build will go on and succeed.
throw new CustomBuildFailedException();

...

public class CustomBuildFailedException: BuildException() {}


推荐阅读