簡體   English   中英

異步協程統一處理

[英]Asynchronous coroutine handling in unity

我已經使用協程進行后端服務調用來檢索我的category.cs文件中的玩家類別:

public override void OnEnter(Page p)
    {
        backend = globalScriptObject.GetComponent<IBackendController>();
        items.Clear ();

        StartCoroutine (backend.GetPlayerProfile ( profile =>{

            this.maxSelectableItems = Mathf.CeilToInt(profile.level/10+1);
            if(this.maxSelectableItems == 7) maxSelectableItems = int.MaxValue;
            DisableSelections();
        }));

GetPlayerProfile(在使用該類的實例后端調用的另一個類中)

public IEnumerator GetPlayerProfile(System.Action<Profile> callback){
        yield return GetPlayerProfile (callback, false);
    }

問題:

由於我正在使用外部服務電話,因此有時會延遲上傳玩家資料。

在執行其余代碼行之前,我需要確保startcoroutine的結果已完成。

我嘗試從互聯網搜索后創建以下類,以確保在執行其余各行之前完成couroutine調用:

    {
    StartCoroutine(FinishFirst(5.0f, DoLast));
     }

     IEnumerator FinishFirst(float waitTime, Action doLast) {
         print("in FinishFirst");
         yield return new WaitForSeconds(waitTime);
         print("leave FinishFirst");
         doLast();
     }


 void DoLast() {
     print("do after everything is finished");
     print("done");
 }

但是,如何在源代碼中使用以上內容是我需要社區的建議的地方。

我還可以在GetPlayerProfile方法中執行yield yield return waitForSec(Float)之類的操作嗎?

謝謝 !!

嘗試使用WaitUntil。

https://docs.unity3d.com/ScriptReference/WaitUntil.html

像這樣:

IEnumerator GetProfile(){
    var profile = null;
    yield GetPlayerProfile((p) => {profile = p});
    yield WaitUntil(p != null);
    this.maxSelectableItems = Mathf.CeilToInt(profile.level/10+1);
    if(this.maxSelectableItems == 7) maxSelectableItems = int.MaxValue;
    DisableSelections();
}

接着...

StartCoroutine(GetProfile);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM