HttpAsyn**重点内容**
下载采用协同,固定更新 每次从下载队列中取一个下载包
下载完成 通过下载包回调通知数据关心者
HttpPackage**重点内容**
下载包 包含 回调 方法,http请求url
对下载的数据 用jeson 解析,通过定义对应的数据对象,用JsonMapper 取转换,注意定义的数据对象一定要和jeson内容对应
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using LitJson;
using System;
/// <summary>
/// 加载数据包
/// </summary>
public class HttpPackage
{
/// <summary>
/// 下载地址
/// </summary>
public string url;
/// <summary>
/// 下载完成
/// </summary>
public Action<string> Downloaded;
public HttpPackage( string url, Action< string> callBack)
{
this.url = url;
Downloaded = callBack;
}
}
public class HttpAsyn : MonoBehaviour {
public static HttpAsyn Instance;
private int coroutineCount;
private int limitCoroutineCount=5;
private Queue<HttpPackage> listPackage = new Queue<HttpPackage>();
private void Awake()
{
Instance = this;
}
/// <summary>
/// 进入下载队列
/// </summary>
/// <param name="package"></param>
public void EnterLoadingQueue(HttpPackage package)
{
if (!listPackage.Contains(package))
{
listPackage.Enqueue(package);
}
}
/// <summary>
/// 进入下载队列
/// </summary>
/// <param name="package">数组</param>
public void EnterLoadingQueue(HttpPackage[] package)
{
for (int i = 0; i < package.Length; i++)
{
if (listPackage.Contains(package[i]))
{
continue;
}
listPackage.Enqueue(package[i]);
}
}
/// <summary>
/// 下载数据
/// </summary>
public void OnUpdate()
{
if (listPackage.Count>0&&coroutineCount<limitCoroutineCount)
{
HttpPackage package = listPackage.Dequeue();
try
{
StartCoroutine(AsynLoadingData(package));
}
catch (System.Exception ex)
{
}
}
}
/// <summary>
/// 异步下载数据
/// </summary>
/// <param name="package"></param>
/// <returns></returns>
public IEnumerator AsynLoadingData(HttpPackage package)
{
coroutineCount += 1;
using (WWW www=new WWW(package.url))
{
yield return www;
if (www.error!=null)
{
Debug.LogError(this.name + ".AsynLoadingData()下载失败" + "url:" + package.url);
EnterLoadingQueue(package);
}
else
{
if (package.Downloaded!=null)
{
if (string.IsNullOrEmpty(www.text) )
{
Debug.LogError(this.name + ".AsynLoadingData() 获取的 www.text 为空 ");
}
else
{
package.Downloaded(www.text);
}
}
}
coroutineCount -= 1;
}
}
public void OnRemovePackage()
{
if(HttpAsyn.Instance!=null)
{
StopAllCoroutines();
listPackage.Clear();
coroutineCount = 0;
}
}
private void Update()
{
OnUpdate();
}
}
public class AnalysisJson
{
public static T Analy<T>(string text) where T:class
{
T o = JsonMapper.ToObject<T>(text);
if (o!=null)
{
return o ;
}
return default(T);
}
public static T GetData<T>(string text) where T : class
{
JsonData table = AnalysisJson.Analy<JsonData>(text);
T t = JsonMapper.ToObject<T>(table["retBody"].ToJson());
return t;
}
}