AssetBundle.cs

本文介绍了一个Unity编辑器脚本,该脚本提供了将文件夹内的资源转换为Bytes文件的功能,并支持针对Android平台进行AssetBundle打包,包括单个文件夹打包和多个子文件夹分别打包。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEngine;
using UnityEditor;

public class AssetBundle
{
    static string OutputPath { get { return "Assets/Bundle"; } }
    static string FileSuffixes { get { return "assetbundle"; } }

    [MenuItem("AssetBundle/Select Folder To Bytes")]
    static void SelectFolderToBytes()
    {
        var output = Application.dataPath + "/Bytes";
        var defaultPath = Application.streamingAssetsPath;
        var openPath = EditorUtility.OpenFolderPanel("Open Folder", defaultPath, null).Replace('\\', '/');
        if (string.IsNullOrEmpty(openPath)) return;
        var name = openPath.Substring(openPath.LastIndexOf('/') + 1);
        foreach (var filePath in GetFolderList(new List<string>(), openPath))
        {
            var file = new FileInfo(filePath);
            var rPath = file.DirectoryName.Substring(openPath.Length).Replace('\\', '/').TrimStart('/');
            var trgPath = output + "/" + name + "/" + rPath;
            if (!Directory.Exists(trgPath)) Directory.CreateDirectory(trgPath);
            var fileName = file.Name.Substring(0, file.Name.LastIndexOf('.'));
            var destFileName = trgPath + "/" + fileName + ".bytes";
            file.CopyTo(destFileName, true);
            Debug.Log("字节化:" + destFileName);
        }
        Debug.Log("[" + name + "]完成转换,输出目录:" + openPath);
    }

    [MenuItem("AssetBundle/Select Folder To Bundle For Android")]
    static void SelectFolderToBundleForAndroid()
    {
        var buildTarget = BuildTarget.Android;
        var defaultPath = Application.dataPath;
        var openPath = EditorUtility.OpenFolderPanel("Open Folder", defaultPath, null).Replace('\\', '/');
        if (string.IsNullOrEmpty(openPath)) return;
        var rootPath = defaultPath.Substring(0, defaultPath.IndexOf("Assets", StringComparison.Ordinal) - 1).Replace('\\', '/');
        var name = openPath.Substring(openPath.LastIndexOf('/') + 1);

        var builds = new List<AssetBundleBuild>();
        var abb = new AssetBundleBuild
        {
            assetBundleName = name + "." + FileSuffixes,
            assetNames = GetFolderList(new List<string>(), openPath, rootPath).ToArray()
        };
        builds.Add(abb);

        if (!Directory.Exists(OutputPath)) Directory.CreateDirectory(OutputPath);
        var outputPath = defaultPath.Substring(0, defaultPath.LastIndexOf("Assets", StringComparison.Ordinal)) + OutputPath;
        foreach (var filePath in builds.Select(ab => outputPath + "/" + ab.assetBundleName).Where(File.Exists))
        {
            File.Delete(filePath);
        }
        BuildPipeline.BuildAssetBundles(OutputPath, builds.ToArray(), BuildAssetBundleOptions.None, buildTarget);

        if (File.Exists(OutputPath + "/" + abb.assetBundleName))
        {
            foreach (var path in abb.assetNames) Debug.Log("打包资源:" + path);
            Debug.Log("资源[" + abb.assetBundleName + "]打包完成,目标平台:" + buildTarget + ",输出目录:" + OutputPath + "/" + abb.assetBundleName);
        }
        else
        {
            Debug.Log("资源[" + abb.assetBundleName + "]打包失败,未找到合适的打包资源");
        }

        ClearUselessFiles(outputPath);
    }

    [MenuItem("AssetBundle/Select Folder To Separate Bundle For Android")]
    static void SelectFolderToSeparateBundleForAndroid()
    {
        var buildTarget = BuildTarget.Android;
        var defaultPath = Application.dataPath;
        var openPath = EditorUtility.OpenFolderPanel("Open Folder", defaultPath, null).Replace('\\', '/');
        if (string.IsNullOrEmpty(openPath)) return;

        var builds = (from dirPath in Directory.GetDirectories(openPath)
                      let dirName = dirPath.Substring(dirPath.Replace('\\', '/').LastIndexOf('/') + 1).ToLower()
                      let dirRoot = dirPath.Substring(0, dirPath.IndexOf("Assets", StringComparison.Ordinal) - 1)
                      select new AssetBundleBuild
                      {
                          assetBundleName = dirName + "." + FileSuffixes,
                          assetNames = GetFolderList(new List<string>(), dirPath, dirRoot).ToArray()
                      }).ToList();

        if (!Directory.Exists(OutputPath)) Directory.CreateDirectory(OutputPath);
        var outputPath = defaultPath.Substring(0, defaultPath.LastIndexOf("Assets", StringComparison.Ordinal)) + OutputPath;
        foreach (var filePath in builds.Select(ab => outputPath + "/" + ab.assetBundleName).Where(File.Exists))
        {
            File.Delete(filePath);
        }
        BuildPipeline.BuildAssetBundles(OutputPath, builds.ToArray(), BuildAssetBundleOptions.None, buildTarget);

        foreach (var abb in builds)
        {
            if (File.Exists(OutputPath + "/" + abb.assetBundleName))
            {
                foreach (var path in abb.assetNames) Debug.Log("打包资源:" + path);
                Debug.Log("资源[" + abb.assetBundleName + "]打包完成,目标平台:" + buildTarget + ",输出目录:" + OutputPath + "/" + abb.assetBundleName);
            }
            else
            {
                Debug.Log("资源[" + abb.assetBundleName + "]打包失败,未找到合适的打包资源");
            }
        }

        ClearUselessFiles(outputPath);
    }

    #region 目录获取
    static List<string> GetFileList(List<string> list, string srcPath, string rootPath = null)
    {
        var filter = new[] { "meta" }.ToList();
        if (!Directory.Exists(srcPath)) Directory.CreateDirectory(srcPath);
        list.AddRange(from path in Directory.GetFiles(srcPath) where !filter.Contains(path.Substring(path.LastIndexOf('.') + 1)) select string.IsNullOrEmpty(rootPath) ? path.Replace('\\', '/') : path.Substring(rootPath.Length + 1).Replace('\\', '/'));
        return list;
    }

    static List<string> GetFolderList(List<string> list, string srcPath, string rootPath = null)
    {
        if (!Directory.Exists(srcPath)) Directory.CreateDirectory(srcPath);
        list = GetFileList(list, srcPath, rootPath);
        return Directory.GetDirectories(srcPath).Aggregate(list, (current, path) => GetFolderList(current, path, rootPath));
    }

    #endregion

    #region 目录操作
    static void DeleteAll(string path)
    {
        foreach (var file in Directory.GetFiles(path).Select(filePath => new FileInfo(filePath)).Where(file => file.Exists))
        {
            file.Delete();
        }
    }

    static void ClearUselessFiles(string path)
    {
        foreach (var file in from filePath in Directory.GetFiles(path)
                             select new FileInfo(filePath) into file
                             let suffix = file.Name.Substring(file.Name.LastIndexOf('.') + 1)
                             where suffix != FileSuffixes
                             select file)
        {
            file.Delete();
        }
    }

    #endregion

}

using UnityEngine; using System; using System.Collections; //using System.Collections.Generic; using XLua; namespace LuaFramework { [LuaCallCSharp] public class ResourceManager : Manager { public static ResourceManager _instance; public LuaFunction onDestroy; private WWW _www; private LuaFunction onProgress; void Awake() { _instance = this; } public static ResourceManager Instance { get { return _instance; } } public void CreatUIObject(string UIPath, string objname, LuaFunction callBack = null) { #if UNITY_EDITOR if (!AppConst.UpdateMode) { string path = "datingui_" + AppConst.UIVersion.ToString() + "/" + UIPath + objname; UnityEngine.Object prefab = Resources.Load(path, typeof(GameObject)); if (prefab != null) { //GameObject obj = Instantiate(Resources.Load<GameObject>(path)); //if (obj != null) //{ GameObject obj = Instantiate(prefab) as GameObject; obj.transform.localScale = Vector3.one; obj.transform.localPosition = Vector3.zero; if (callBack != null) { callBack.Call(obj); } //} }else { if (callBack != null) { callBack.Call(null); } } }else { StartCoroutine(LoadObj(AppConst.FrameworkRoot + "/datingui_" + AppConst.UIVersion + "/" + UIPath + objname + ".u3d", objname, callBack)); } #else StartCoroutine(LoadObj(AppConst.FrameworkRoot + "/datingui_" + AppConst.UIVersion + "/" + UIPath + objname + ".u3d", objname, callBack)); #endif } public void CreatGameObject(string GameName, string path, string objname, LuaFunction callBack = null) { #if UNITY_EDITOR if (!AppConst.UpdateMode) { //try //{ GameObject obj = Instantiate(Resources.Load<GameObject>("gameui"+AppConst.UIVersion+"/" + GameName + "/" + path + objname)); obj.transform.localScale = Vector3.one; obj.transform.localPosition = Vector3.zero; if (callBack != null) { callBack.Call(obj); } //}catch (Exception ex) //{ // Debug.LogError(ex.Message); //} } else { string path_ = AppConst.FrameworkRoot + "/gameui" + AppConst.UIVersion + "/" + GameName + "/" + path + objname + ".u3d"; StartCoroutine(LoadObj(path_, objname, callBack)); } #else string path_ = AppConst.FrameworkRoot + "/gameui"+AppConst.UIVersion +"/" + GameName + "/" + path + objname + ".u3d"; StartCoroutine(LoadObj(path_, objname, callBack)); #endif } public void setProgressUpdate(LuaFunction callback) { onProgress = callback; } public void resetProgressUpdate() { onProgress = null; _www = null; } float jindus = 0.0f; void Update() { #if UNITY_ANDROID if (_www != null && onProgress != null) { onProgress.Call(_www.progress); //Debug.Log(www.progress); } #else //if (jindutiao) // jindutiao.value = jindus; if (onProgress != null) { onProgress.Call(jindus); //Debug.Log(www.progress); } #endif } IEnumerator LoadObj(string bundlePath, string ObjName, LuaFunction callBack = null) { AssetBundle built = null; #if UNITY_ANDROID string path_2 = "file:///" + bundlePath; WWW www = new WWW(@path_2); if (onProgress != null) { _www = www; } yield return www; if (www.error == null) { yield return built = www.assetBundle; } else { Debug.Log("www null-------- " + path_2); } #else string path_ = bundlePath; byte[] data = null;// = OpenFile.GetFileData(path_); if (System.IO.File.Exists(path_)) { System.IO.FileStream file_ = new System.IO.FileStream(path_, System.IO.FileMode.Open, System.IO.FileAccess.Read); data = new byte[file_.Length]; int redline = 0; int allnum = 0; while (true) { byte[] reddata = new byte[1024000]; redline = file_.Read(reddata, 0, (int)reddata.Length); if (redline <= 0) { jindus = 1.0f; break; } else { //Debug.LogError(redline); System.Array.Copy(reddata, 0, data, allnum, redline); allnum += redline; jindus = (float)allnum / (float)data.Length; } yield return null; } file_.Close(); file_.Dispose(); } if (data != null) { yield return built = AssetBundle.LoadFromMemory(data); } #endif if (built != null) { GameObject obj = Instantiate(built.LoadAsset(ObjName)) as GameObject; obj.transform.localScale = Vector3.one; obj.transform.localPosition = Vector3.zero; if (callBack != null) { callBack.Call(obj); } built.Unload(false); }else { if (callBack != null) { callBack.Call(null); } } #if UNITY_ANDROID www.Dispose(); #endif } void OnDestroy() { if (onDestroy != null) { onDestroy.Call(); } } } }这个是UNITY5.3版本LUA代码,运行时的报错的日志文件在下面,请帮我检查一下代码并修改,但是不要影响到别的文件调用,-----CompilerOutput:-stderr---------- Assets/Scripts/Manager/ResourceManager.cs(16,49): error CS1519: Unexpected symbol `=>' in class, struct, or interface member declaration Assets/Scripts/Manager/ResourceManager.cs(16,62): error CS1519: Unexpected symbol `?' in class, struct, or interface member declaration Assets/Scripts/Manager/ResourceManager.cs(16,98): error CS1519: Unexpected symbol `(' in class, struct, or interface member declaration Assets/Scripts/Manager/ResourceManager.cs(46,60): error CS1519: Unexpected symbol `=>' in class, struct, or interface member declaration Assets/Scripts/Manager/ResourceManager.cs(46,74): error CS1519: Unexpected symbol `=' in class, struct, or interface member declaration Assets/Scripts/Manager/ResourceManager.cs(46,80): error CS1519: Unexpected symbol `;' in class, struct, or interface member declaration Assets/Scripts/Manager/ResourceManager.cs(47,56): error CS1519: Unexpected symbol `=>' in class, struct, or interface member declaration Assets/Scripts/Manager/ResourceManager.cs(47,70): error CS1519: Unexpected symbol `=' in class, struct, or interface member declaration Assets/Scripts/Manager/ResourceManager.cs(47,76): error CS1519: Unexpected symbol `;' in class, struct, or interface member declaration Assets/Scripts/Manager/ResourceManager.cs(48,57): error CS1519: Unexpected symbol `=>' in class, struct, or interface member declaration Assets/Scripts/Manager/ResourceManager.cs(48,68): error CS1519: Unexpected symbol `=' in class, struct, or interface member declaration Assets/Scripts/Manager/ResourceManager.cs(48,74): error CS1519: Unexpected symbol `;' in class, struct, or interface member declaration Assets/Scripts/Manager/ResourceManager.cs(64,27): error CS1525: Unexpected symbol `<internal>' Assets/Scripts/Manager/ResourceManager.cs(73,27): error CS1525: Unexpected symbol `<internal>' Assets/Scripts/Manager/ResourceManager.cs(82,42): error CS1525: Unexpected symbol `<internal>' Assets/Scripts/Manager/ResourceManager.cs(82,13): warning CS0642: Possible mistaken empty statement Assets/Scripts/Manager/ResourceManager.cs(105,29): error CS1525: Unexpected symbol `.', expecting `[', or `identifier' Assets/Scripts/Manager/ResourceManager.cs(106,29): error CS1525: Unexpected symbol `.', expecting `[', or `identifier' Assets/Scripts/Manager/ResourceManager.cs(110,35): error CS1525: Unexpected symbol `<internal>' Assets/Scripts/Manager/ResourceManager.cs(112,29): error CS1525: Unexpected symbol `.', expecting `[', or `identifier' Assets/Scripts/Manager/ResourceManager.cs(113,26): error CS1525: Unexpected symbol `.', expecting `[', or `identifier' Assets/Scripts/Manager/ResourceManager.cs(127,29): error CS1525: Unexpected symbol `.', expecting `[', or `identifier' Assets/Scripts/Manager/ResourceManager.cs(140,31): error CS1525: Unexpected symbol `<internal>' Assets/Scripts/Manager/ResourceManager.cs(145,95): error CS1525: Unexpected symbol `<internal>' Assets/Scripts/Manager/ResourceManager.cs(151,33): error CS1525: Unexpected symbol `.', expecting `[', or `identifier' Assets/Scripts/Manager/ResourceManager.cs(181,14): error CS1519: Unexpected symbol `if' in class, struct, or interface member declaration Assets/Scripts/Manager/ResourceManager.cs(181,25): error CS1519: Unexpected symbol `!=' in class, struct, or interface member declaration Assets/Scripts/Manager/ResourceManager.cs(184,28): error CS1519: Unexpected symbol `return' in class, struct, or interface member declaration Assets/Scripts/Manager/ResourceManager.cs(184,42): error CS1519: Unexpected symbol `;' in class, struct, or interface member declaration Assets/Scripts/Manager/ResourceManager.cs(186,39): error CS1041: Identifier expected Assets/Scripts/Manager/ResourceManager.cs(187,55): error CS1018: Keyword `this' or `base' expected Assets/Scripts/Manager/ResourceManager.cs(186,17): error CS1520: Class, struct, or interface method must have a return type Assets/Scripts/Manager/ResourceManager.cs(189,30): error CS1519: Unexpected symbol `(' in class, struct, or interface member declaration Assets/Scripts/Manager/ResourceManager.cs(191,16): error CS1518: Expected `class', `delegate', `enum', `interface', or `struct' Assets/Scripts/Manager/ResourceManager.cs(197,29): error CS0116: A namespace can only contain types and namespace declarations Assets/Scripts/Manager/ResourceManager.cs(230,27): error CS1525: Unexpected symbol `<internal>' Assets/Scripts/Manager/ResourceManager.cs(229,13): warning CS0642: Possible mistaken empty statement Assets/Scripts/Manager/ResourceManager.cs(221,22): error CS0116: A namespace can only contain types and namespace declarations Assets/Scripts/Manager/ResourceManager.cs(236,21): error CS0116: A namespace can only contain types and namespace declarations Assets/Scripts/Manager/ResourceManager.cs(253,14): error CS0116: A namespace can only contain types and namespace declarations Assets/Scripts/Manager/ResourceManager.cs(259,5): error CS8025: Parsing error
最新发布
07-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值