【问题标题】:Asynchronous coroutine handling in unity统一处理异步协程
【发布时间】:2019-03-28 21:55:38
【问题描述】:

我已使用协程进行后端服务调用以检索我的 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 return waitForSec(Float) 的操作吗?

谢谢!!

【问题讨论】:

  • 我不确定是什么问题。您的其余代码 (DisableSelections();) 应该仅在 FinishFirst 函数完成后才能工作。
  • 听起来async - await 可能比协程更适合您的需求。
  • 感谢derHugo的回复,我正在使用unity 3D来开发这个游戏应用程序。Unity通常建议使用协程,这就是问题所在。

标签: c# unity3d


【解决方案1】:

尝试使用 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);

【讨论】:

    猜你喜欢
    • 2018-06-08
    • 2019-10-17
    • 1970-01-01
    • 1970-01-01
    • 2020-11-29
    • 1970-01-01
    • 2013-09-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多