Unity 简单实现资源管理类加载AssetBundle

基于Unity用C#语言编写一个资源管理类,要求如下:
使用协程加载加载AssetBundle,支持优先级队列,尽量考虑加载新能。

设置打包编辑器:

#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.IO;

public class AssetBundle
{
    //编辑器扩展,在菜单栏Assets下生成Build AssetBundles菜单
    [MenuItem("Assets/Build AssetBundles")]
    //进行资源打包
    static void BuildAllAssetBundles()
    {
        //打包之前要保证文件夹存在,不存在的话会报错
        //使用相对路径保存
        string dir = "AssetBundle";
        if (Directory.Exists(dir) == false)
        {
            Directory.CreateDirectory(dir);
        }
        //BuildPipeline是UnityEditor中用于打包的类,其中的BuildAssetBundle用于AssetBundle打包
        //dir:存储的路径
        //BuildAssetBundleOptions:表示压缩式的算法   None为LZMA算法
        //BuildTarget: 表示用于什么平台
        BuildPipeline.BuildAssetBundles(dir, BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows64);

        Debug.Log("打包成功!");
    }
}
#endif

第一种实现方式:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking; //UnityWebRequest
using UnityEngine.UI;

public class RS : MonoBehaviour //资源管理类,进行资源优先级排序并进行资源加载
{
    /*
    //UnityWebRequest加载测试实例,用来检测一开始是否加载成功
    IEnumerator Start()
    {//使用UnityWebRequest

        string uri = @"http://localhost:56000/AssetBundle/image1.unity3d"; //获取请求,注意端口号
        UnityWebRequest request = UnityWebRequest.GetAssetBundle(uri);
        yield return request.SendWebRequest(); //等待请求发送完
        Debug.Log(request);

        //DownloadHandlerAssetBundle.GetContent(request); 注意,此时仅仅是取得ab对象
        //AssetBundle ab = (request.downloadHandler as DownloadHandlerAssetBundle).assetBundle;
        UnityEngine.AssetBundle ab = DownloadHandlerAssetBundle.GetContent(request);
        Debug.Log(ab);

        if (ab != null)
        {
            Debug.Log(ab + "ab success"); //输出结果:1.unity success        --测试加载成功
        }
        else
        {
            Debug.Log(ab + "ab not success");
        }
    }
    */

    public enum LoadLevel  //定义加载优先级枚举
    {
        LOW = 1,
        HIGHT = 2
    }

    //在Inspection设置对应的变量属性
    //保存panel中对应的image对象
    public GameObject[] image;
    private int imageIndex = 0;
    //传入对应image的资源名,注意保持资源名和包名一致
    public string[] resName;
    //传入对应image的资源优先级
    public LoadLevel[] resLevel;

    //加载服务器资源的路径
    private string url = @"http://localhost:50949/AssetBundle/";
    //协程对象,控制只有一个协程运行
    private Coroutine load;
    //高优先级队列与低优先级队列,不需要用List泛型
    ArrayList hightList = new ArrayList();
    ArrayList lowList = new ArrayList();


    public void LoadList(string resname, LoadLevel level)  //队列处理函数
    {
        //进行对应优先级队列
        if ((int)level == 2)
        {
            hightList.Add(resname);
        }
        else
        {
            lowList.Add(resname);
        }
    }

    IEnumerator LoadRes()  //定义一个调用协程
    {   
        string resname = "";
        int i = 1;
        while (hightList.Count + lowList.Count != 0) //在每一帧中使用协程从队列中获取图片并打印信息
        {
            if (hightList.Count != 0)
            {
                resname = (string)hightList[0];
                hightList.RemoveAt(0);
            }
            else if (lowList.Count != 0)
            {
                resname = (string)lowList[0];
                lowList.RemoveAt(0);
            }

            //使用UnityWebRequest
            UnityWebRequest request = UnityWebRequest.GetAssetBundle(url + resname + ".unity3d");
            //等待请求发送完
            yield return request.SendWebRequest();
            Debug.Log(request);
            //加载Ab包
            UnityEngine.AssetBundle ab = DownloadHandlerAssetBundle.GetContent(request);
            //if (ab != null)
            //Debug.Log(ab);
            //加载图片资源
            Sprite resource = ab.LoadAsset(resname);
            //Debug.Log(resource);
            //引用资源
            image[imageIndex].GetComponent().sprite = resource;
            imageIndex++;
            //清理AB包
            ab.Unload(false);
            //协程置空
            load = null;

            Debug.Log("第" + i + "帧");
            Debug.Log("load res succeed:" + resname);

            //分帧加载,每一帧提取5条数据
            if (imageIndex % 5 == 0)
            {
                yield return null; //在下一帧执行
                i++;
                Debug.Log("分帧加载停顿处");
            }


        }
    }
    
    // Use this for initialization
    void Start()
{
    for (int i = 0; i < resName.Length; i++) //初始化优先级队列的数据
    {
        LoadList(resName[i], resLevel[i]);
    }

    //开始协程进行加载,在协程内进行分帧加载
    StartCoroutine(LoadRes());
}

// Update is called once per frame
void Update()
{
}
}

第二种实现方式:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking; //UnityWebRequest
using UnityEngine.UI;

public class RS : MonoBehaviour //资源管理类,进行资源优先级排序并进行资源加载
{
    /*
    //UnityWebRequest加载测试实例,用来检测一开始是否加载成功
    IEnumerator Start()
    {//使用UnityWebRequest

        string uri = @"http://localhost:56000/AssetBundle/image1.unity3d"; //获取请求,注意端口号
        UnityWebRequest request = UnityWebRequest.GetAssetBundle(uri);
        yield return request.SendWebRequest(); //等待请求发送完
        Debug.Log(request);

        //DownloadHandlerAssetBundle.GetContent(request); 注意,此时仅仅是取得ab对象
        //AssetBundle ab = (request.downloadHandler as DownloadHandlerAssetBundle).assetBundle;
        UnityEngine.AssetBundle ab = DownloadHandlerAssetBundle.GetContent(request);
        Debug.Log(ab);

        if (ab != null)
        {
            Debug.Log(ab + "ab success"); //输出结果:1.unity success        --测试加载成功
        }
        else
        {
            Debug.Log(ab + "ab not success");
        }
    }
    */

    public enum LoadLevel  //定义加载优先级枚举
    {
        LOW = 1,
        HIGHT = 2
    }

    //在Inspection设置对应的变量属性
    //保存panel中对应的image对象
    public GameObject[] image;
    private int imageIndex = 0;
    //传入对应image的资源名,注意保持资源名和包名一致
    public string[] resName;
    //传入对应image的资源优先级
    public LoadLevel[] resLevel;

    //加载服务器资源的路径
    private string url = @"http://localhost:56000/AssetBundle/";
    //协程对象,控制只有一个协程运行
    private Coroutine load;
    //高优先级队列与低优先级队列,不需要用List泛型
    ArrayList hightList = new ArrayList();
    ArrayList lowList = new ArrayList();

    public void LoadList(string resname, LoadLevel level)  //队列处理函数
    {
        //进行对应优先级队列
        if ((int)level == 2)
        {
            hightList.Add(resname);
        }
        else
        {
            lowList.Add(resname);
        }
    }

    IEnumerator LoadRes(string resname)  //定义一个调用协程,根据传入的名称进行相应资源的加载
    {
        Debug.Log(resname);
        //使用UnityWebRequest
        UnityWebRequest request = UnityWebRequest.GetAssetBundle(url + resname + ".unity3d");
        //等待请求发送完
        yield return request.SendWebRequest();
        Debug.Log(request);
        //加载Ab包
        UnityEngine.AssetBundle ab = DownloadHandlerAssetBundle.GetContent(request);
        //if (ab != null)
        //Debug.Log(ab);
        //加载图片资源
        Sprite resource = ab.LoadAsset(resname);
        //Debug.Log(resource);
        //引用资源
        image[imageIndex].GetComponent().sprite = resource;
        imageIndex++;
        //清理AB包
        ab.Unload(false);
        //协程置空
        load = null;
        Debug.Log("load res succeed:" + resname);
    }

    // Use this for initialization
    void Start()
    {
        for (int i = 0; i < resName.Length; i++) //初始化优先级队列的数据
        {
            LoadList(resName[i], resLevel[i]);
        }

    }

    // Update is called once per frame
    void Update()
    {
        if (hightList.Count + lowList.Count != 0) //在每一帧中使用协程根据队列进行图片加载和信息打印
        {
            if (load == null) //当协程未运行时,启动协程进行加载,当协程运行时,说明正在加载图片
            {
                if (hightList.Count != 0)
                {
                    load = StartCoroutine("LoadRes", (string)hightList[0]);
                    hightList.RemoveAt(0);
                }
                else if (lowList.Count != 0)
                {
                    load = StartCoroutine("LoadRes", (string)lowList[0]);
                    lowList.RemoveAt(0);
                }
            }
        }
    }
}

具体项目如下所示:
Unity 简单实现资源管理类加载AssetBundle_第1张图片
需要的可以自行下载:https://download.csdn.net/download/a834595603/11232570

你可能感兴趣的:(游戏开发相关知识与技巧)