U3D协程Coroutine之WWW与Update()的并行测试
生活随笔
收集整理的這篇文章主要介紹了
U3D协程Coroutine之WWW与Update()的并行测试
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
U3D協(xié)程Coroutine之WWW與Update()的并行測(cè)試
using System.Collections; using UnityEditor; using UnityEngine; using UnityEngine.UI;/************************************************************************/ /* UnityEngine.WWW 下載與Update()的并行測(cè)試,UNITY5.35f */ /************************************************************************/ public class wwwTest : MonoBehaviour {WWW www;IEnumerator Start () {//下載文件是一個(gè)RAR,比較大,要下載幾分鐘才能完成,//運(yùn)行發(fā)現(xiàn),下載和Update()并行,游戲正常運(yùn)行,調(diào)試發(fā)現(xiàn)創(chuàng)建并使用WWW對(duì)象并不會(huì)開啟新線程//這說(shuō)明WWW也是利用協(xié)程來(lái)實(shí)現(xiàn)下載的,如果是這樣,下載速度應(yīng)該會(huì)受Update()函數(shù)調(diào)用頻率的影響,經(jīng)測(cè)試發(fā)現(xiàn)下載速度并不受影響,不明覺厲 //【補(bǔ)記】在協(xié)程函數(shù)中使用Thread.sleep(1000)將會(huì)卡住主線程,不要在下載時(shí)這樣用,這樣只是在為其它進(jìn)程節(jié)省時(shí)間,降低下載速度。www = new WWW ("http://psoft.33lc.com:801/small/directxruntimes_x86.rar");yield return www;//下載開始,直到下載完成才會(huì)執(zhí)行本函數(shù)剩余的代碼。
// Load the object asynchronously
AssetBundleRequest request = bundle.LoadAssetAsync ("myObject", typeof(GameObject));
// Wait for completion
yield return request;//加載完成后才會(huì)執(zhí)行后面的代碼
if(www == null){EditorUtility.DisplayDialog ("", "download stoped", "ok");yield break;//協(xié)程將拋棄后面所有代碼//yield return null; //協(xié)程返回后下次回來(lái)會(huì)執(zhí)行下面的代碼,由于下載失敗,下面的操作將出錯(cuò) }if(www.isDone){string info = "download complete";if (!string.IsNullOrEmpty (www.error))//有些平臺(tái)上不允許string為null,則這時(shí)返回空串"";//yield return null; //協(xié)程返回后下次回來(lái)會(huì)執(zhí)行下面的代碼,由于下載失敗,下面的操作將出錯(cuò)yield break;EditorUtility.DisplayDialog ("info", info, "ok");}else{EditorUtility.DisplayDialog ("error", "download error", "ok");yield return null;}EditorUtility.DisplayDialog ("finally", "end", "ok");RawImage img = GetComponent<RawImage> ();img.texture = www.texture;}void Update () {if(Input.GetKeyDown (KeyCode.Space)){Debug.Log ("is done: " + www.progress); //顯示下載進(jìn)度 }else if(Input.GetKeyDown (KeyCode.LeftControl)){if(Input.GetKey (KeyCode.W)){//組合鍵測(cè)試 CTRL + W// 詭異現(xiàn)象,注意:先按CTRL再W無(wú)法進(jìn)入到這里,先W再CTRL則可以進(jìn)入到這里。//GetKeyDown在按鍵期間只觸發(fā)一次,且不能再觸發(fā)其它按鍵;GetKey在按鍵期間一直不斷觸發(fā),且可以同時(shí)再觸發(fā)其它鍵//因此兩個(gè)GetKeyDown(A)&&GetKeyDown(B)不能實(shí)現(xiàn)組合鍵。//GetKey(A) && GetKey(B)可以實(shí)現(xiàn)組合鍵,對(duì)游戲效率影響較大//GetKeyDown(A) && GetKey(B)也可以實(shí)現(xiàn)組合鍵,對(duì)游戲效率影響較小//相機(jī)漫游類的操作需要按鍵每幀或每幾幀觸發(fā),因此必須使用getkeyif(EditorUtility.DisplayDialog ("", "你確定要終止下載嗎", "ok", "cancel")){www.Dispose ();www = null;}}}if(Input.GetKey (KeyCode.A) && Input.GetKey(KeyCode.B)){Debug.Log ("A AND B ===============");}transform.Rotate (0, 2, 0);} }
?
posted on 2016-10-21 19:51 時(shí)空觀察者9號(hào) 閱讀(...) 評(píng)論(...) 編輯 收藏
與50位技術(shù)專家面對(duì)面20年技術(shù)見證,附贈(zèng)技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的U3D协程Coroutine之WWW与Update()的并行测试的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: U3D5.3.5f Monodevelo
- 下一篇: Unity 协程Coroutine综合测