c# - Unity - 等待 HTTP 请求解析

标签 c# unity3d

函数如下,不知道有没有更简洁的写法:

private static WWW WaitUntilResolved (WWW request)
{
    bool success = true;
    float timeout = 5000, timer = 0;

    while (!request.isDone) {
        if (timer > timeout) {
            success = false;
            break;
        }
        timer += Time.deltaTime;
    }

    if (success && request.error == null)
        return request;
    else {
        request.Dispose ();
        return null;
    }
}

附言。 WWW 是原生统一类:https://docs.unity3d.com/ScriptReference/WWW.html

最佳答案

你真的在使用 WWWisDone错误的。如果必须使用isDone,则必须将它放在while 循环中。您还必须在 while 循环中使用 yield return null; yield 否则游戏将卡住,直到下载完成。这整件事需要 coroutine所以这个函数必须做成协程函数。

你真的不需要 isDone。这在您想了解下载进度时使用。

下面是使用 isDone 的正确方法:

private static IEnumerator WaitUntilResolved(WWW request)
{
    while (!request.isDone)
    {
        Debug.Log("Download Stat: " + request.progress);

        //Wait each frame in each loop OR Unity would freeze
        yield return null;
    }

    if (string.IsNullOrEmpty(request.error))
    {
        //Success
    }
}

如果您不需要知道下载进度,那么您应该使用以下内容:

private static IEnumerator WaitUntilResolved(WWW request)
{
    yield return request;
    if (string.IsNullOrEmpty(request.error))
    {
        //Success
    }
}

最后,不能直接调用协程函数。你必须使用 StartCoroutine函数来做到这一点:

WWW www = new WWW("www.yahoo.com");
StartCoroutine(WaitUntilResolved(www));

编辑:

How do I set a timeout for the coroutine?

大多数 WebRequest 教程都使用计时器。在使用 WWW API 的 Unity 中,您不需要这样做。这里没有必要,因为这是一个非阻塞操作。如果您一定要看下面的代码。

private static IEnumerator WaitUntilResolved(WWW request)
{
    float timeout = 5000, timer = 0;

    while (!request.isDone)
    {
        Debug.Log("Download Stat: " + request.progress);

        timer += Time.deltaTime;
        if (timer >= timeout)
        {
            Debug.Log("Timeout happened");
            //Break out of the loop
            yield break;
        }
        //Wait each frame in each loop OR Unity would freeze
        yield return null;
    }

    if (string.IsNullOrEmpty(request.error))
    {
        //Success
    }
}

如果您需要返回下载状态,请参阅 this解释如何做到这一点的帖子。

关于c# - Unity - 等待 HTTP 请求解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44682376/

相关文章:

c# - 深度复制 BindingList<Object>

unity3d - Unity脚本在编辑器中运行,但无法构建

unity3d - 在 Unity3D 中, "setting"网格的边界会做什么或实现什么?

c# - 对象没有出现在 Hololens 中 Vuforia 标记的顶部/中心,如何解决?

android - 如何在 Android/iOS 设备上调试 unity3d?

c# - VBNET 中 (IntPtr)1 的等价物?

c# - 关于JAVA、C#等中的序列化

c# - “开放式”REST 框架 (.Net)

c# - 如何创建人物编辑器?

c# - Unity 的 Android 插件给出错误