1. 程式人生 > >uniyt http 非同步獲取資料

uniyt http 非同步獲取資料

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; } }