Unity3D引擎WWW资源加载和缓存(AssetBundle、Texture、Audio)

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

public class DownLoadCenter : MonoBehaviour {

    //定义回调
    public delegate void SetValueCallBack(Object obj);
    //声明回调
    public SetValueCallBack CallBack;

    //文本回调
    public delegate void SetValueCallBack_Text(string txt);
    public SetValueCallBack_Text CallBack_Text;

    public ArrayList _loadedBundle = new ArrayList();
    public ArrayList _loadedBundleName = new ArrayList();
    /// <summary>
    /// 加载进度
    /// </summary>
    public float LoadProgress = 0f;

    private bool loadStart = false;

    private WWW w;

    void Update()
    {
        if (loadStart)
        {
            LoadProgress = w.progress;
            if (LoadProgress == 1.0f)
                loadStart = false;
        }
    }

    /// <summary>
    /// url是网络加载地址,name是资源名称(带后缀),type是读取类型(assetbundle,texture,audio3种类型),id是图片加载的时候传入的唯一名称(替代name),isUnloadNow是是否发消息之后就释放资源(非assetbundle)
    /// </summary>
    /// <param name="url"></param>
    /// <param name="name"></param>
    /// <param name="type"></param>
    /// <param name="poolDic"></param>
    public void LoadAsset(string url, string name, string type , string id = null , bool isUnloadNow = true)
    {
        //如果已经加载过直接返回
        if(type == "assetbundle" && _loadedBundleName.Contains(name)){
            for (int i = 0; i < _loadedBundle.Count; i++ )
            {
                Dictionary<string, Object> _dic = _loadedBundle[i] as Dictionary<string,Object>;
                if (_dic.ContainsKey(name))
                {
                    AssetBundle _bundle = _dic[name] as AssetBundle;
                    CallBack(_bundle);
                    return;
                }
            }
        }
        //TODO:version对比
        if(false){
            Debug.Log("读取本地模型");
            StartCoroutine(LoadAssetFromLocal(Application.persistentDataPath + "/" + name, type, name, id , isUnloadNow));
        }
        else
        {
            Debug.Log("读取网络模型");
            StartCoroutine(LoadAssetFromWWW(url + name, type, name, id , isUnloadNow));
        }
    }

    //读取本地文件
    IEnumerator LoadAssetFromLocal(string path, string type, string name, string id , bool isUnloadNow)
    {
        string _name = name;
        if (id != null)
        {
            _name = id;
        }
#if UNITY_EDITOR
        string filepath = "file:///" + Application.persistentDataPath + "/" + _name;

#elif UNITY_IPHONE
      string filepath = Application.persistentDataPath + "/" + _name;

#elif UNITY_ANDROID
      string filepath = "jar:file://" +  Application.persistentDataPath + "/" + _name;

#endif
        Debug.Log("本地获取路径:"+filepath);
        w = new WWW(filepath);
        loadStart = true;
        yield return w;
        if (w.isDone && w.error == null)
        {
            Dictionary<string, Object> _dic = new Dictionary<string, Object>();
            Object _asset = null;
            string _strAsset = null;

            if (type == "assetbundle")
            {
                _asset = w.assetBundle;
                //存入已加载bundle
                _dic.Add(name, _asset);
                _loadedBundle.Add(_dic);
                _loadedBundleName.Add(name);
            }
            else if (type == "texture")
            {
                _asset = w.texture;
            }
            else if (type == "audio")
            {
                _asset = w.audioClip;
            }
            else if(type == "text")
            {
                _strAsset = w.text;
            }
            else
            {
                Debug.LogError("资源加载类型错误:" + type);
            }

            //判断类型是否是 文本
            if(type == "text")
            {
                CallBack_Text(_strAsset);
            }
            else
            {
                CallBack(_asset);
            }

            if (isUnloadNow)
            {
                Resources.UnloadUnusedAssets();
            }

        }
        else {
            Debug.LogError("资源加载出错:" + w.error.ToString());
        }


    }

    //读取网络文件,并存入本地
    IEnumerator LoadAssetFromWWW(string url, string type, string name, string id ,bool isUnloadNow)
    {
        Debug.Log(url);
        w = new WWW(url);
        loadStart = true;
        yield return w;
        if (w.isDone)
        {
            Dictionary<string, Object> _dic = new Dictionary<string, Object>();
            Object _asset = null;
            string _strAsset = null;

            if (type == "assetbundle")
            {
                _asset = w.assetBundle;
                //存入已加载bundle
                _dic.Add(name, _asset);
                _loadedBundle.Add(_dic);
                _loadedBundleName.Add(name);
            }
            else if (type == "texture")
            {
                _asset = w.texture;
            }
            else if (type == "audio")
            {
                _asset = w.audioClip;
            }
            else if (type == "text")
            {
                _strAsset = w.text;
            }
            else
            {
                Debug.LogError("资源加载类型错误:" + type);
            }


            //判断类型是否是 文本
            if (type == "text")
            {
                string[] _fileNames=Directory.GetFiles(Application.persistentDataPath+"/");
                foreach(string file in _fileNames)
                {
                    File.Delete(file);
                }

                CallBack_Text(_strAsset);
                CreateTextFile(Application.persistentDataPath+"/", name, _strAsset);
            }
            else
            {
                byte[] _assetByte = w.bytes;
                int length = _assetByte.Length;

                //写入模型到本地  
                string _name = name;
                if (id != null)
                {
                    _name = id;
                }
                CreateFile(Application.persistentDataPath + "/" + _name, _assetByte, length);
                Debug.Log("本地url:" + Application.persistentDataPath + "/" + _name);
                //TODO:储存新version文件

                CallBack(_asset);
            }

            if (isUnloadNow)
            {
                Resources.UnloadUnusedAssets();
            }

        }
    }


    /** 
   * path:文件创建目录 
   * name:文件的名称 
   *  info:写入的内容 
   */
    void CreateFile(string path, byte[] info, int length)
    {
        //文件流信息  
        //StreamWriter sw;  
        Stream sw;
        FileInfo t = new FileInfo(path);
        t.Delete();
        sw = t.Create();
        //以行的形式写入信息  
        //sw.WriteLine(info);  
        sw.Write(info, 0, length);
        //关闭流  
        sw.Close();
        //销毁流  
        sw.Dispose();
    }


    /** 
  * path:文件创建目录 
  * name:文件的名称 
  *  info:写入的内容 
  */
    void CreateTextFile(string path, string name, string info)
    {
        //文件流信息  
        StreamWriter sw;
        FileInfo t = new FileInfo(path + "/" + name);
        t.Delete();
        sw = t.CreateText();
        //以行的形式写入信息  
        sw.WriteLine(info);
        //关闭流  
        sw.Close();
        //销毁流  
        sw.Dispose();
    }
}

其调用方式也很简单,如下代码:

void Start()
{
    DownLoadCenter down = GetComponent<DownLoadCenter>();
    down.Callback = OnCallback;
    down.LoadAsset("资源路径","资源名称","资源类型");
}

private void OnCallback(string type, Object obj)
{
    //在回调函数中编写所要执行的代码
    AssetBundle ab = obj as AssetBundle;
    GameObject go = ab.LoadAsset<GameObject>("预设名称");
}

猜你喜欢

转载自blog.csdn.net/lizhenxiqnmlgb/article/details/80694981