1. 程式人生 > >自動打包01及選擇檔案路徑_學習記錄

自動打包01及選擇檔案路徑_學習記錄

自動打包多與自動上傳一起使用,比如固定時間點或者SVN提交之後,自動出包,然後上傳到指定內網網址或共享資料夾。

在此只記錄一下關於自動打包的學習過程,只限於Windows打Android包,包含自動打包及其相關回調,編輯器自定義視窗,呼叫系統視窗選擇路徑,讀取Windows桌面路徑等功能。實際使用意義不大,還需要做一些功能的完善及擴充套件~~

感謝大佬們優秀的文章,對我幫助非常大:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEditor.Callbacks;
using System.IO;
using System.Runtime.InteropServices;
using System;
using Microsoft.Win32;
//Assets/Editor資料夾下Test
namespace SimpleFrame.Tool
{
    //確認視窗, 可用快捷鍵啟動
    public class AndroidPackageWindow : EditorWindow
    {
        [MenuItem("MyTools/Package/Build Android Package #&b")]
        public static void Package()
        {
            //彈出確認視窗
            EditorWindow.GetWindow(typeof(AndroidPackageWindow), false, "Build Android Package Window");
        }
        string showStr;
        Texture2D defaultIcon;
        //
        string apkPath, apkName;
        void OnEnable()
        {
            //確認資訊
            showStr = "\nBuild Platform : Android";
            showStr += "\n\nCompany Name : " + PlayerSettings.companyName;
            showStr += "\n\nProduct Name : " + PlayerSettings.productName;
            showStr += "\n\nPackage Name : " + PlayerSettings.applicationIdentifier;
            showStr += "\n\nBundle Version : " + PlayerSettings.bundleVersion;
            showStr += "\n\nBundle Version Code : " + PlayerSettings.Android.bundleVersionCode;
            //圖示Iocn
            Texture2D[] texture2Ds = PlayerSettings.GetIconsForTargetGroup(BuildTargetGroup.Android);
            defaultIcon = texture2Ds.Length > 0 ? texture2Ds[0] : null;
            //打包預設路徑及預設檔名
            apkPath = GetDesktopPath();
            apkName = PlayerSettings.productName;
        }
        //獲取Windows使用者桌面路徑
        //https://blog.csdn.net/csethcrm/article/details/6163431
        string GetDesktopPath()
        {
            RegistryKey folders = Registry.CurrentUser;
            string s = @"/software/microsoft/windows/currentversion/explorer/shell folders";
            s = s.Remove(0, 1) + @"/";
            while (s.IndexOf(@"/") != -1)
            {
                folders = folders.OpenSubKey(s.Substring(0, s.IndexOf(@"/")));
                s = s.Remove(0, s.IndexOf(@"/") + 1);
            }
            return folders.GetValue("Desktop").ToString();
        }
        void OnGUI()
        {
            GUILayout.Space(10);
            GUILayout.Label("Please Make Sure");
            defaultIcon = EditorGUILayout.ObjectField(defaultIcon, typeof(Texture2D), true) as Texture2D;
            EditorGUILayout.TextArea(showStr);
            GUILayout.Space(5);
            apkPath = EditorGUILayout.TextField("Apk Path : ", apkPath);
            if(!Directory.Exists(apkPath))
                EditorGUILayout.TextArea("Apk Path Is Error");
            apkName = EditorGUILayout.TextField("Apk Name : ", apkName);
            if (string.IsNullOrEmpty(apkName))
                EditorGUILayout.TextArea("Apk Name Is Empty");
            //呼叫系統視窗,選擇儲存路徑
            if (GUILayout.Button("Select Path"))
            {
                OpenFileName openFileName = new OpenFileName();        
                openFileName.structSize = Marshal.SizeOf(openFileName);
                openFileName.filter = "apk(*.apk)\0All files(*.*)";
                openFileName.file = new string(new char[256]);
                openFileName.maxFile = openFileName.file.Length;
                openFileName.fileTitle = new string(new char[64]);
                //openFileName.fileTitle = apkName;
                openFileName.maxFileTitle = openFileName.fileTitle.Length;
                openFileName.initialDir = apkPath.Replace('/', '\\');//預設路徑
                openFileName.title = "Select Path";
                openFileName.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000008;
                if (LocalDialog.GetSaveFileName(openFileName))
                {
                    //擷取字串
                    apkName = openFileName.fileTitle.Split('.')[0];
                    apkPath = openFileName.file.Replace('\\', '/');
                    apkPath = apkPath.Split('.')[0];
                    apkPath = apkPath.Replace("/" + apkName, "");
                    Debug.Log(apkPath + " / " + apkName);
                }
            }
            GUILayout.Space(10);
            if (GUILayout.Button("Cancel"))
                this.Close();
            GUILayout.Space(5);
            if (Directory.Exists(apkPath) && !string.IsNullOrEmpty(apkName))
            {
                if (GUILayout.Button("Sure"))
                {
                    this.Close();
                    PackageTool.Build(apkPath, apkName);
                }
            }
            this.Repaint();
        }
        void OnDisable()
        {
            showStr = null;
            defaultIcon = null;
        }
    }
    //https://blog.csdn.net/yzd1733638228/article/details/77989210
    public class PackageTool
    {
        //打包操作
        public static void Build(string apkPath, string apkName)
        {
            if (!Directory.Exists(apkPath) || string.IsNullOrEmpty(apkName))
                return;
            if (BuildPipeline.isBuildingPlayer)
                return;
            //設定打包平臺、標籤
            PlayerSettings.SetScriptingDefineSymbolsForGroup(BuildTargetGroup.Android, null);
            //打包場景路徑
            List<string> sceneNames = new List<string>();
            foreach (EditorBuildSettingsScene scene in EditorBuildSettings.scenes)
            {
                if (scene != null &amp;&amp; scene.enabled)
                {
                    sceneNames.Add(scene.path);
                    Debuger.Log(scene.path);
                }
            }
            string path = apkPath + "/" + apkName + ".apk";
            //開始打包
            BuildPipeline.BuildPlayer(sceneNames.ToArray(), path, BuildTarget.Android, BuildOptions.None);
        }
        //回撥  打包後操作
        [PostProcessBuild(1)]
        public static void AfterBuild(BuildTarget target, string pathToBuiltProject)
        {
            Debug.Log("Build Success  " + target + "  " + pathToBuiltProject);
            //https://blog.csdn.net/zp288105109a/article/details/81366343
            //可在此開啟檔案或資料夾
            System.Diagnostics.Process.Start(pathToBuiltProject);
        }
    }
    //https://blog.csdn.net/m0_37283423/article/details/78180487
    //呼叫系統視窗
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
    public class OpenFileName
    {
        //資料接收類
        public int structSize = 0;
        public IntPtr dlgOwner = IntPtr.Zero;
        public IntPtr instance = IntPtr.Zero;
        public String filter = null;
        public String customFilter = null;
        public int maxCustFilter = 0;
        public int filterIndex = 0;
        public String file = null;
        public int maxFile = 0;
        public String fileTitle = null;
        public int maxFileTitle = 0;
        public String initialDir = null;
        public String title = null;
        public int flags = 0;
        public short fileOffset = 0;
        public short fileExtension = 0;
        public String defExt = null;
        public IntPtr custData = IntPtr.Zero;
        public IntPtr hook = IntPtr.Zero;
        public String templateName = null;
        public IntPtr reservedPtr = IntPtr.Zero;
        public int reservedInt = 0;
        public int flagsEx = 0;
    }
    //呼叫系統視窗函式
    public class LocalDialog
    {
        //連結指定系統函式  //開啟檔案對話方塊
        [DllImport("Comdlg32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]
        public static extern bool GetOpenFileName([In, Out] OpenFileName ofn);
        public static bool GetOFN([In, Out] OpenFileName ofn)
        {
            return GetOpenFileName(ofn);
        }
        //連結指定系統函式  //另存為對話方塊
        [DllImport("Comdlg32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]
        public static extern bool GetSaveFileName([In, Out] OpenFileName ofn);
        public static bool GetSFN([In, Out] OpenFileName ofn)
        {
            return GetSaveFileName(ofn);
        }
    }
}