当前位置:   article > 正文

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

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();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250
  • 251
  • 252
  • 253
  • 254
  • 255
  • 256
  • 257
  • 258
  • 259
  • 260
  • 261
  • 262
  • 263
  • 264
  • 265
  • 266
  • 267
  • 268
  • 269

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

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>("预设名称");
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

这里写图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/332747?site
推荐阅读
相关标签
  

闽ICP备14008679号