unity-Editor AssetBundle打包等编辑器扩展工具整理

整理一些unity方便的快捷操作工具
因为在编辑扩展工具,因此脚本必须放在Editor目录下,并且引用相应的库 这里我把我使用到的库全放出来

using System;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.SceneManagement;
using Object = UnityEngine.Object;

变量

    public static BuildAssetBundleOptions sBuildOption = //BuildAssetBundleOptions.None;
            BuildAssetBundleOptions.DeterministicAssetBundle |
            BuildAssetBundleOptions.ForceRebuildAssetBundle |
            BuildAssetBundleOptions.StrictMode;

        //private static string resExtension = "*.mp3,*.xml,*.txt,*.prefab,*.png,*.jpg,*.tga,*.unity";
        
        static List<string> resExtension = new List<string> { ".wav", ".ogg", ".mp3", ".xml", ".prefab", ".txt", ".png", ".jpg", ".tga", ".unity", ".fbx" };

0. 快捷键

  1. & ➡ALT
  2. #➡SHIFT
  3. %➡CTRL

1.设置所选的图片为天空球资源

        [MenuItem("Assets/NewTool/SetToSky &1")]  //&1 设置快捷键ALT+1  
        public static void SetToSky()
        {
            Skybox skybox = Camera.main.GetComponent<Skybox>();
            if (skybox == null)
            {
                skybox = Camera.main.gameObject.AddComponent<Skybox>();
            }
            Material mat = AssetDatabase.LoadMainAssetAtPath("assets/localres/Materials/shopInsideView_test.mat") as Material;
            skybox.material = new Material(mat);
            skybox.material.SetTexture("_MainTex", Selection.activeObject as Texture2D);
        }

2.改变所选图片尺寸(此处设置为4096,2048)

    [MenuItem("Assets/NewTool/ChangeTexSize &2")]
        public static void ChageSizeTex()
        {
            Object[] selectedAsset = Selection.GetFiltered(typeof(Texture), SelectionMode.DeepAssets);
            for (int i = 0; i < selectedAsset.Length; i++)
            {
                Texture2D tex = selectedAsset[i] as Texture2D;
                TextureImporter ti = (TextureImporter)AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(tex));
                ti.maxTextureSize = 4096;
                ti.isReadable = true;
                ti.wrapMode = TextureWrapMode.Clamp;
                AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(tex));
                string imagePath = AssetDatabase.GetAssetPath(tex);
                byte[] fileData = File.ReadAllBytes(imagePath);
                tex.LoadImage(fileData);
                Texture2D temp = ScaleTexture(tex, 4096, 2048);
                byte[] pngData = temp.EncodeToJPG();
                string miniImagePath = imagePath.Replace(".png", "_min.jpg");
                File.WriteAllBytes(miniImagePath, pngData);
                AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(tex));
            }
        }
     private static Texture2D ScaleTexture(Texture2D source, int targetWidth, int targetHeight)
        {
            Texture2D result = new Texture2D(targetWidth, targetHeight, source.format, true);
            Color[] rpixels = result.GetPixels(0);
            float incX = ((float)1 / source.width) * ((float)source.width / targetWidth);
            float incY = ((float)1 / source.height) * ((float)source.height / targetHeight);
            for (int px = 0; px < rpixels.Length; px++)
            {
                rpixels[px] = source.GetPixelBilinear(incX * ((float)px % targetWidth), incY * ((float)Mathf.Floor(px / targetWidth)));
            }
            result.SetPixels(rpixels, 0);
            result.Apply();
            return result;
        }

3.打包所选的文件成合并的AssetBundle(该目录下所有子文件)

 	[MenuItem("Assets/NewTool/打包AB/打包成合并的文件")]
    public static void ExportAssets2OneBundle()
        {
        	// 获取文件名,选择的文件最顶层的文件目录的名称
            string save_name = Selection.GetFiltered(typeof(Object), SelectionMode.TopLevel)[0].name;
            string outputPath = EditorUtility.SaveFilePanel("Save Resource", Application.streamingAssetsPath, save_name, "unity3d").Replace("\\", "/");
            if (string.IsNullOrEmpty(outputPath))
            {
                return;
            }

            Object[] selection = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);
            if (selection.Length == 0)
            {
                return;
            }

            string filePath;
            List<string> assetPath = new List<string>();
            for (int idx = 0, count = selection.Length; idx < count; ++idx)
            {
                filePath = AssetDatabase.GetAssetPath(selection[idx]).Replace("\\", "/");
                if (File.Exists(filePath))
                {
                    assetPath.Add(filePath);
                }
            }
            ExportRes2OneBundle(outputPath, assetPath.ToArray(), EditorUserBuildSettings.activeBuildTarget);
        } 
   public static void ExportRes2OneBundle(string outputPath, string[] assetPath, BuildTarget buildTarget)
        {
            string msg = string.Format("打包到{0}", outputPath);
            EditorUtility.DisplayProgressBar("资源打包", msg, 0.1f);
            if (Directory.Exists("Export") == false)
            {
                Directory.CreateDirectory("Export");
            }
            string fileName = outputPath.GetHashCode().ToString();
            AssetBundleBuild[] buildMap = new AssetBundleBuild[1];
            buildMap[0].assetBundleName = fileName;
            buildMap[0].assetNames = assetPath;
            EditorUtility.DisplayProgressBar("资源打包", msg, 0.5f);
            BuildPipeline.BuildAssetBundles("Export", buildMap, sBuildOption, buildTarget);
            EditorUtility.DisplayProgressBar("资源打包", msg, 0.9f);
            string srcPath = string.Format("Export/{0}", fileName);
            if (File.Exists(outputPath))
            {
                File.Delete(outputPath);
            }
            File.Move(srcPath, outputPath);
            EditorUtility.ClearProgressBar();
            Debug.Log(string.Format("{0}->{1}", srcPath, outputPath));
        }

4.打包所选的文件成独立的AssetBundle

     [MenuItem("Assets/NewTool/打包AB/打包成独立的文件")]
        public static void ExportAssets2IndependentBundles()
        {
            string outputPath = EditorUtility.SaveFolderPanel("Save Resource", Application.dataPath, "").Replace("\\", "/");
            if (string.IsNullOrEmpty(outputPath))
            {
                return;
            }

            Object[] selection = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);
            if (selection.Length == 0)
            {
                return;
            }

            Debug.Log(outputPath);
            //string outputFilePath;
            string filePath;
            List<string> assetPath = new List<string>();
            for (int idx = 0, count = selection.Length; idx < count; ++idx)
            {
                filePath = AssetDatabase.GetAssetPath(selection[idx]).Replace("\\", "/");
                if (File.Exists(filePath))
                {
                    assetPath.Add(filePath);
                }
            }
            ExportRes2IndependentBundles(outputPath, assetPath.ToArray(), EditorUserBuildSettings.activeBuildTarget);
        }
  public static void ExportRes2IndependentBundles(string outputPath, string[] assetPath, BuildTarget buildTarget)
        {
            string msg = string.Format("打包到{0}", outputPath);
            EditorUtility.DisplayProgressBar("资源打包", msg, 0.1f);
            if (Directory.Exists("Temp") == false)
            {
                Directory.CreateDirectory("Temp");
            }
            AssetBundleBuild[] builds = new AssetBundleBuild[assetPath.Length];
            string outputFilePath;
            for (int idx = 0, count = assetPath.Length; idx < count; ++idx)
            {
                outputFilePath = string.Format("{0}/{1}", outputPath, Path.GetDirectoryName(assetPath[idx]));
                outputFilePath = string.Format("{0}/{1}.unity3d", outputFilePath, Path.GetFileNameWithoutExtension(assetPath[idx]));
                builds[idx].assetBundleName = outputFilePath.GetHashCode().ToString();
                builds[idx].assetNames = new string[] { assetPath[idx] };
                EditorUtility.DisplayProgressBar("资源打包", msg, 0.1f + idx * 1.0f / count * 0.3f);
            }

            BuildPipeline.BuildAssetBundles("Temp", builds, sBuildOption, EditorUserBuildSettings.activeBuildTarget);
            EditorUtility.DisplayProgressBar("资源打包", msg, 0.7f);

            string srcFilePath;
            for (int idx = 0, count = assetPath.Length; idx < count; ++idx)
            {
                outputFilePath = string.Format("{0}/{1}", outputPath, Path.GetDirectoryName(assetPath[idx]));
                outputFilePath = string.Format("{0}/{1}.unity3d", outputFilePath, Path.GetFileNameWithoutExtension(assetPath[idx]));
                srcFilePath = string.Format("Temp/{0}", outputFilePath.GetHashCode().ToString());
                if (File.Exists(srcFilePath) == false)
                {
                    Debug.LogError(string.Format("{0} is invalid file", srcFilePath));
                    Debug.LogError(string.Format("{0}->{1} Failed", srcFilePath, outputFilePath));
                    continue;
                }
                if (File.Exists(outputFilePath))
                {
                    File.Delete(outputFilePath);
                }
                if (Directory.Exists(Path.GetDirectoryName(outputFilePath)) == false)
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(outputFilePath));
                }
                try
                {
                    File.Move(srcFilePath, outputFilePath);
                    File.Delete(string.Format("{0}.manifest", srcFilePath));
                }
                catch (Exception ex)
                {
                    Debug.LogError(string.Format("{0}->{1} Failed! Exception: \n{2}", srcFilePath, outputFilePath, ex));
                }
                EditorUtility.DisplayProgressBar("资源打包", msg, 0.7f + idx * 1.0f / count * 0.3f);
            }
            EditorUtility.ClearProgressBar();
        }

5.输出所选的AB内容列表

    [MenuItem("Assets/NewTool/打包AB/输出AssetBundle的内容列表")]
        public static void ListAssetNames()
        {
            string filePath = AssetDatabase.GetAssetPath(Selection.activeObject);
            if (filePath.EndsWith(".unity3d", true, null) == false)
            {
                return;
            }
            AssetBundle ab = AssetBundle.LoadFromFile(filePath);
            string[] assetName = ab.GetAllAssetNames();
            string output = string.Format("asset count:{0}", assetName.Length);
            for (int idx = 0, count = assetName.Length; idx < count; ++idx)
            {
                output = string.Format("{0}\n{1}", output, assetName[idx]);
            }
            Debug.Log(output);
            ab.Unload(false);
            ab = null;
        }
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值