如何通过 Unity 编辑器脚本强制构建过程失败?

Jor*_*vão 5 unity-game-engine

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

我试过使用一个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");
    }
}
Run Code Online (Sandbox Code Playgroud)

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

我正在使用 Unity 2018.3.8f1。

mar*_*rmd 8

截至 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);
}
Run Code Online (Sandbox Code Playgroud)


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

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

...

public class CustomBuildFailedException: BuildException() {}

Run Code Online (Sandbox Code Playgroud)


小智 1

您可以使用 OnValidate() ,这似乎正是您正在寻找的。假设您想在构建之前确保对 UI 文本组件的引用不为空,在应该具有文本引用的脚本中,您添加

private void OnValidate()
{
     if (text == null)
     {
          Debug.LogError("Text reference is null!");
     }
}
Run Code Online (Sandbox Code Playgroud)

在构建过程中调用 Debug.LogError 实际上会导致构建失败。