Unity 命令行打包

首先需要在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/UnityUnity安装目录
-quit在其他命令执行完毕后退出 Unity Editor。这可能导致错误消息被隐藏(但是,它们仍会出现在 Editor.log 文件中)。
-batchmode以批处理模式运行 Unity。在批处理模式下,Unity 无需人工交互即可运行命令行参数。它还会禁止需要人工交互的弹出窗口(例如 Save Scene 窗口);但是,Unity 编辑器本身会像往常一样打开。使用命令行参数时,您应该始终以批处理模式运行 Unity,因为它允许自动化运行而不会中断。
-executeMethodUnity 打开项目后以及可选的资源服务器更新完成后,立即执行静态方法。可以使用此命令来执行连续集成,执行单元测试,进行构建或准备数据等任务。
-projectPath在指定路径下打开项目。如果路径名包含空格,请将其用引号引起来。
-scene:自定义参数,可通过System.Environment.GetCommandLineArgs();获取所有参数

官方文档:https://docs.unity3d.com/cn/2020.2/Manual/CommandLineArguments.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值