首页 > 手游开发 > Unity3D > Unity3D中打包时触发的事件
2022
06-06

Unity3D中打包时触发的事件

在Unity3D打包时,其过程是可以监听到各种事件的.例如打包开始,打包结束,切换平台,编译shader等.

打包开始

在编辑器中实现IPreprocessBuild接口,以下是官方例子:

using UnityEditor;
using UnityEditor.Build;
using UnityEngine;
class MyCustomBuildProcessor : IPreprocessBuild
{    
  public int callbackOrder { get { return 0; } }    
  public void OnPreprocessBuild(BuildTarget target, string path)    
  {        
    Debug.Log("MyCustomBuildProcessor.OnPreprocessBuild for target " + target + " at path " + path);    
  }
}

打包结束

在编辑器中添加监听 PostProcessBuildAttribute

using UnityEngine;
using UnityEditor;
using UnityEditor.Callbacks;
public class MyBuildPostprocessor 
{    
  [PostProcessBuildAttribute(1)]   
  public static void OnPostprocessBuild(BuildTarget target, string pathToBuiltProject)
  {        
    Debug.Log( pathToBuiltProject );        
  }
}

编译shader前

在编辑器中实现IPreprocessShaders接口

using System.Collections.Generic;using UnityEditor.Build;
using UnityEditor.Rendering;
using UnityEngine;using UnityEngine.Rendering;
class MyCustomBuildProcessor : IPreprocessShaders
{
    ShaderKeyword m_Blue;
    public MyCustomBuildProcessor()
    {
        m_Blue = new ShaderKeyword("_BLUE");
    }
    public int callbackOrder { get { return 0; } }
    public void OnProcessShader(Shader shader, ShaderSnippetData snippet, IList<ShaderCompilerData> data)
    {
        for (int i = data.Count - 1; i >= 0; --i)
        {
            if (!data[i].shaderKeywordSet.IsEnabled(m_Blue))
                continue;
            data.RemoveAt(i);
        }
    }
}

打包场景

在编辑器里实现IProcessScene接口

using UnityEditor;
using UnityEditor.Build;
using UnityEngine;
class MyCustomBuildProcessor : IProcessScene{
    public int callbackOrder { get { return 0; } }
    public void OnProcessScene(UnityEngine.SceneManagement.Scene scene)
    {
        Debug.Log("MyCustomBuildProcessor.OnProcessScene " + scene.name);
    }
}

切换平台

在编辑器里实现IActiveBuildTargetChanged接口

using UnityEngine;
using UnityEditor;using UnityEditor.Build;
public class ActiveBuildTargetListener : IActiveBuildTargetChanged
{
    public int callbackOrder { get { return 0; } }
    public void OnActiveBuildTargetChanged(BuildTarget previousTarget, BuildTarget newTarget)
    {
        Debug.Log("Switched build target to " + newTarget);
    }
}

有了这些事件,就可以很方便的在打包前后加入自己的个性化需求了
例如在打包前要删除掉一部分AB包里面所包含的测试场景,测试资源等.

最后编辑:
作者:搬运工

留下一个回复

你的email不会被公开。