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

时间:2019-03-16 16:15:26

标签: unity3d

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

我尝试使用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。

2 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分:1)

从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() {}