IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 游戏开发 -> AssetBundle加载 -> 正文阅读

[游戏开发]AssetBundle加载

场景存放规则

导出AssetBundle资源
文件夹路径信息
Assets文件夹
|------GResources
| |-----Material
| |-----Prefabs
| |-----Scene
| | └------场景名文件夹(例子:Main)
| | └------------场景文件(例子:Main.unity)
| |-----Prefabs

AssetBundle的加载

public class AssetBundleManager : MonoBehaviour
{
	private AssetBundleManifest manifest;
	private string mAssetBundlePath { get { return string.Format("{0}/{1}", Application.streamingAssetsPath, platform); } }
    /// <summary>
    /// 已加载的Assetbundle
    /// </summary>
    Dictionary<string, AssetBundle> All_Assetbundle = new Dictionary<string, AssetBundle>();
    /// <summary>
    /// 正在加载的AssetBundle
    /// </summary>
    List<string> AllCurrentAssetBundle = new List<string>();
    
#if UNITY_STANDALONE_WIN
    private static string platform = "Windows";
#elif UNITY_ANDROID
    private static string platform = "Android";
#elif UNITY_IOS || UNITY_IPHONE
    private static string platform = "IOS";
#else
    private static string platform = "Windows";
#endif


    private void GetManifest()
    {
        string assetbundlepath = $"{mAssetBundlePath}/{platform}";
        AssetBundle assetBundle = AssetBundle.LoadFromFile(assetbundlepath);
        if (assetBundle != null)
        {
            manifest = assetBundle.LoadAsset<AssetBundleManifest>("AssetBundleManifest");
        }
        else
        { 
        }
    }
#region 同步加载

    public T Load<T>(string varPath) where T : Object
    {
        return LoadAssets<T>(varPath);
    }
    private T LoadAssets<T>(string varPath) where T : Object
    {
    	string filename = Path.GetFileNameWithoutExtension(varPath);
    	string assetbundlename = GetAssetBundleName(varPath);
    	AssetBundle assetBundle = LoadAssetBundle(assetbundlename);
    	if (assetBundle == null)
        {
            return null;
        }
        else
        {
            //加载依赖
            T assets = assetBundle.LoadAsset<T>(filename);
            return assets;
        }
	}
	private AssetBundle LoadAssetBundle(string assetbundlename)
	{
		if (All_Assetbundle.ContainsKey(assetbundlename))
		{
			return All_Assetbundle[assetbundlename];
		}
        else
        {
            if (!AllCurrentAssetBundle.Contains(assetbundlename))
            {
            	string assetbundlepath = $"{mAssetBundlePath}/{assetbundlename}";
                AssetBundle assetBundle = AssetBundle.LoadFromFile(assetbundlepath);
                All_Assetbundle.Add(assetbundlename, assetBundle);
                //加载相关依赖
                LoadAssetBundleManifest(assetBundle, assetbundlename);
                return assetBundle;
            }
            return null;
        }
	}
	private void LoadAssetBundleManifest(AssetBundle assetBundle,string assetbundlename)
    {
        if (manifest == null)
        {
            GetManifest();
        }
        //获取依赖
        if (manifest != null)
        {
            string[] Dependencies = manifest.GetDirectDependencies(assetbundlename);

            if (Dependencies != null)
            {
                for (int i = 0; i < Dependencies.Length; i++)
                {
                    LoadAssetBundle(Dependencies[i]);
                }
            }
        }
	}
#endregion

#region 异步加载
	public void LoadAsync<T>(string varPath, LoadCallBack<T> Callback) where T : Object
    {
        StartCoroutine(LoadAsyncAssets(varPath, Callback));
    }
    /// <summary>
    /// 异步加载Assets
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="varPath"></param>
    /// <param name="Callback"></param>
    /// <returns></returns>
    IEnumerator LoadAsyncAssets<T>(string varPath, LoadCallBack<T> Callback) where T : Object
    {
        yield return null;
        string filename = Path.GetFileNameWithoutExtension(varPath);
        string assetbundlename = GetAssetBundleName(varPath);
        AssetBundle assetBundle = null;
        yield return StartCoroutine(LoadAsyncAssetBundle(assetbundlename, (varassetbundle) =>
        {
            assetBundle = varassetbundle;
        }));
        if (assetBundle != null)
        {
            T assets = assetBundle.LoadAsset<T>(filename);
            Callback.Invoke(varPath, assets);
        }
        else
        {
            Callback.Invoke(varPath, null);
        }
    }
    /// <summary>
    /// 异步加载AssetBundle
    /// </summary>
    /// <param name="varAssetBundlePath"></param>
    /// <param name="assetBundleFinish"></param>
    /// <returns></returns>
    IEnumerator LoadAsyncAssetBundle(string varAssetBundleName, LoadAssetBundleFinish assetBundleFinish)
    {
        //确保Key值统一标准
        varAssetBundleName = varAssetBundleName.Replace("\\", "/");

        if (All_Assetbundle.ContainsKey(varAssetBundleName))
        {
            //获取AssetBundle
            AssetBundle assetBundle = All_Assetbundle[varAssetBundleName];
            //完成回调
            assetBundleFinish?.Invoke(assetBundle);
		}
        else if (AllCurrentAssetBundle.Contains(varAssetBundleName))
        {
            while (AllCurrentAssetBundle.Contains(varAssetBundleName))
            {
                yield return null;
            }
            //获取AssetBundle
            AssetBundle assetBundle = All_Assetbundle[varAssetBundleName];
            //完成回调
            assetBundleFinish?.Invoke(assetBundle);
        }
        else
        {
        	//添加加载标记
            AllCurrentAssetBundle.Add(varAssetBundleName);
            string assetbundlepath = $"{mAssetBundlePath}/{varAssetBundleName}";
            AssetBundle tempAssetBundle = null;
            AssetBundleCreateRequest tempAssetbundleQuest = AssetBundle.LoadFromFileAsync(assetbundlepath);
            while (!tempAssetbundleQuest.isDone)
            {
                yield return null;
            }
            tempAssetBundle = tempAssetbundleQuest.assetBundle;
            All_Assetbundle.Add(varAssetBundleName, tempAssetBundle);
            //加载依赖
            yield return StartCoroutine(LoadAsyncAssetBundleManifest(tempAssetBundle, varAssetBundleName));
            //完成回调
            assetBundleFinish?.Invoke(tempAssetBundle);
            //移除加载标记
            AllCurrentAssetBundle.Remove(varAssetBundleName);
		}
	}
    /// <summary>
    /// 加载AssetBundle的依赖
    /// </summary>
    /// <param name="assetBundle"></param>
    /// <param name="filename"></param>
    /// <returns></returns>
    IEnumerator LoadAsyncAssetBundleManifest(AssetBundle assetBundle, string filename)
    {
        if (manifest == null)
        {
            GetManifest();
        }
        if (manifest != null)
        {
            string[] Dependencies = manifest.GetDirectDependencies(filename);
            if (Dependencies != null)
            {
                for (int i = 0; i < Dependencies.Length; i++)
                {
                	yield return StartCoroutine(LoadAsyncAssetBundle(Dependencies[i], null));
                }
           	}
		}
	}  
#endregion

#region 加载场景

	public void LoadScene(string varSceneName, LoadSceneCallBack varloadFinish, LoadSceneCallBack varLoadFail)
	{
		string assetsbundlename = $"gresources/scene/{varSceneName.ToLower()}.{AssetBundleExtension.Variant}";
		StartCoroutine(LoadAsyncScene(assetsbundlename, varSceneName, varloadFinish, varLoadFail));
	}
	IEnumerator LoadAsyncScene(string assetsbundlename, string varScene, LoadSceneCallBack varloadFinish, LoadSceneCallBack varLoadFail)
	{
		AssetBundle.UnloadAllAssetBundles(false);
		yield return null;
		AssetBundle assetBundle = null;
		yield return StartCoroutine(LoadAsyncAssetBundle(assetsbundlename, (varAssetBundle) => {
			assetBundle = varAssetBundle;
		}));
        if (assetBundle != null)
        {
            AsyncOperation operation = UnityEngine.SceneManagement.SceneManager.LoadSceneAsync(varScene, UnityEngine.SceneManagement.LoadSceneMode.Single);
            operation.allowSceneActivation = true;
            while (!operation.isDone)
            {
                yield return null;
            }
            varloadFinish?.Invoke();
        }
        else
        {
            varLoadFail?.Invoke();
        }
        yield return null;
    }
#endregion
	/// <summary>
    /// 获取assetbundle名称
    /// </summary>
    /// <param name="varAssetbunlePath"></param>
    /// <returns></returns>
    private string GetAssetBundleName(string varPath)
    {
        string tempPath = Path.GetDirectoryName(varPath).ToLower();
        tempPath = tempPath.Replace("\\", "/");
        string assbundlename = "";
        int index = tempPath.IndexOf("gresources/");
        if (index >= 0)
        {
        	//index += "assets".Length + 1;
            assbundlename= tempPath.Remove(0, index);

            return $"{assbundlename}.{AssetBundleExtension.Variant}";
        }
        else
        {
            return $"{varPath}.{AssetBundleExtension.Variant}";
        }
    }    
}

AssetBundle拓展文件

public class AssetBundleExtension
{
	public const string Variant = "bundle";
}
  游戏开发 最新文章
6、英飞凌-AURIX-TC3XX: PWM实验之使用 GT
泛型自动装箱
CubeMax添加Rtthread操作系统 组件STM32F10
python多线程编程:如何优雅地关闭线程
数据类型隐式转换导致的阻塞
WebAPi实现多文件上传,并附带参数
from origin ‘null‘ has been blocked by
UE4 蓝图调用C++函数(附带项目工程)
Unity学习笔记(一)结构体的简单理解与应用
【Memory As a Programming Concept in C a
上一篇文章      下一篇文章      查看所有文章
加:2021-08-04 11:32:18  更:2021-08-04 11:32:27 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年12日历 -2024/12/27 6:03:50-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码
数据统计