首先需要在Unity中编写静态方法。然后通过命令行调用。
一、Editor脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;
public class BatchMode
{
static List<string> levels = new List<string>();
[MenuItem("Tools/Build/BuildWebGL")]
public static void BuildWebGL()
{
string sceneName = "";
//获取命令行参数
string[] args = System.Environment.GetCommandLineArgs();
if (args.Length > 1)
{
foreach (var arg in args)
{
if (arg.Contains("-scene:"))
{
sceneName = arg.Split(':')[1];
}
}
}
if (string.IsNullOrEmpty(sceneName))
{
RefreshScene();
}
else
{
RefreshScene(sceneName);
}
foreach (var scene in EditorBuildSettings.scenes)
{
Debug.Log(string.Format("scene path: {0}, enabled: {1}", scene.path, scene.enabled));
if (!scene.enabled)
continue;
levels.Add(scene.path);
}
// 打包
BuildPipeline.BuildPlayer(levels.ToArray(), "Build", BuildTarget.WebGL, BuildOptions.None);
}
// 向PlayerSetting中添加需要打包的场景
public static void RefreshScene(string sceneName = "Demo")
{
string resourcePath = Application.dataPath;
string[] absolutePaths = Directory.GetFiles(resourcePath + "/Games/Scenes", "*.unity", SearchOption.AllDirectories);
List<EditorBuildSettingsScene> list = new List<EditorBuildSettingsScene>();
for (int i = 0; i < absolutePaths.Length; i++)
{
string path = "Assets" + absolutePaths[i].Remove(0, resourcePath.Length);
path = path.Replace("\\", "/");
if(path.Contains(sceneName))
list.Add(new EditorBuildSettingsScene(path, true));
}
EditorBuildSettings.scenes = list.ToArray();
}
}
二、命令行指令
/Applications/Unity/Hub/Editor/2021.3.29f1c1/Unity.app/Contents/MacOS/Unity -quit -batchmode -executeMethod BatchMode.BuildWebGL -projectPath ~/Project/vocjc-demo -scene:HuanYang
指令 | 解释 |
---|---|
/Unity.app/Contents/MacOS/Unity | Unity安装目录 |
-quit | 在其他命令执行完毕后退出 Unity Editor。这可能导致错误消息被隐藏(但是,它们仍会出现在 Editor.log 文件中)。 |
-batchmode | 以批处理模式运行 Unity。在批处理模式下,Unity 无需人工交互即可运行命令行参数。它还会禁止需要人工交互的弹出窗口(例如 Save Scene 窗口);但是,Unity 编辑器本身会像往常一样打开。使用命令行参数时,您应该始终以批处理模式运行 Unity,因为它允许自动化运行而不会中断。 |
-executeMethod | Unity 打开项目后以及可选的资源服务器更新完成后,立即执行静态方法。可以使用此命令来执行连续集成,执行单元测试,进行构建或准备数据等任务。 |
-projectPath | 在指定路径下打开项目。如果路径名包含空格,请将其用引号引起来。 |
-scene: | 自定义参数,可通过System.Environment.GetCommandLineArgs();获取所有参数 |
官方文档:https://docs.unity3d.com/cn/2020.2/Manual/CommandLineArguments.html