如何在Unity3d协程中获得返回值(int)?

时间:2017-09-08 05:47:30

标签: c# unity3d return coroutine

如何在协程中获得返回值? 但是,getElapseSecond()函数不应该在协程内。

 WWW www;
public IEnumerator requestNowTime()
{
    www = new WWW(url);

    yield return www;
}


public IEnumerator getNowTime()
{
    yield return StartCoroutine(requestNowTime());
}

public int getElapseSecond()
{
    StartCoroutine(getNowTime()); 
    // You are trying to load data from a www stream which has not completed the download yet.

    int totalSeconds = 0;
    DateTime dt = Convert.ToDateTime(www.text);
    TimeSpan compareTime = dt - Convert.ToDateTime(getTime());
    totalSeconds = (int)compareTime.TotalSeconds;  

    return totalSeconds;  //0
}

1 个答案:

答案 0 :(得分:1)

你不能简单地在正常的功能中等待协程的结果,除非你希望你的游戏冻结,直到你的答案在那里使用while循环等。

我可以建议您采用以下策略:使用回调。回调是当前函数/协同程序完成后将调用的函数。收到WWW中的requestNowTime参数后,请调用一个计算已用时间的函数。在同一个函数中,当你完成计算时,使用一个回调,它将是原始调用者的函数,它将能够首先按预期使用结果。

WWW www;

// Call this function to start the computing process
public void ProcessElapsedSeconds(Action functionToCallWhenDone)
{
    StartCoroutine(requestNowTime(functionToCallWhenDone));
}

public IEnumerator requestNowTime(Action callback)
{
    www = new WWW(url);

    OnTimeReceived(www, functionToCallWhenDone);
}  

void OnTimeReceived(WWW www, Action functionToCallWhenDone)
{
    int totalSeconds = 0;
    DateTime dt = Convert.ToDateTime(www.text);
    TimeSpan compareTime = dt - Convert.ToDateTime(getTime());
    totalSeconds = (int)compareTime.TotalSeconds;  

    functionToCallWhenDone(totalSeconds);
}