WWW

作者:追风剑情 发布于:2019-7-16 17:59 分类:Unity3d

示例一:实现一个简单的加载队列

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

/// <summary>
/// WWW加载队列
/// </summary>
public class WWWQueue : MonoBehaviour
{
    private List<WWWLoader> list = new List<WWWLoader>();

    private void Awake()
    {
        DontDestroyOnLoad(gameObject);
    }

    private void Update()
    {
        for (int i=0; i < list.Count; i++)
        {
            WWW www = list[i].www;
            if (!www.isDone)
                continue;

            if (!string.IsNullOrEmpty(www.error))
            {
                Debug.LogErrorFormat("{0}\n{1}", www.error, www.url);
                RemoveAt(i);
                continue;
            }

            AssetBundle ab = www.assetBundle;
            Action<AssetBundle> callback = list[i].callback;
            bool cancel = list[i].cancel;
            if (!cancel && callback != null)
                callback(ab);
            ab.Unload(false);//释放镜像资源
            www.Dispose();

            RemoveAt(i);
        }
    }

    private void RemoveAt(int index)
    {
        if (index >= list.Count)
            return;
        if (index == list.Count - 1)
        {
            list.RemoveAt(index);
            return;
        }

        //优化
        var obj = list[index];
        list[index] = list[list.Count-1];
        list[list.Count-1] = obj;
        list.RemoveAt(list.Count - 1);
    }

    // 加载
    public void Load(string url, Action<AssetBundle> callback)
    {
        WWW www = new WWW(url);
        WWWLoader loader = new WWWLoader(www, callback);
        list.Add(loader);
    }

    // 取消
    public void Cancel(string url)
    {
        for (int i=0; i<list.Count; i++)
        {
            if (list[i].www.url == url)
            {
                list[i].cancel = true;
            }
        }
    }

    private class WWWLoader
    {
        public Action<AssetBundle> callback;
        public WWW www;
        public bool cancel = false;

        public WWWLoader(WWW www, Action<AssetBundle> callback)
        {
            this.www = www;
            this.callback = callback;
        }

        public void Dispose()
        {
            callback = null;
            if (www != null)
                www.Dispose();
            www = null;
        }
    }
}

标签: Unity3d

Powered by emlog  蜀ICP备18021003号   sitemap

川公网安备 51019002001593号