在Unity中,WWW类是异步的还是同步的? [英] In Unity is a WWW class asynchronous or synchronous?

查看:479
本文介绍了在Unity中,WWW类是异步的还是同步的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解如何在Unity中编写WWW调用.根据此处的说明 http://docs.unity3d.com/ScriptReference/WWW.html我可以检查isDone属性,但是在同一页上的示例中,它没有尝试检查isDone.

I am trying to understand how to write a WWW call in Unity. According to the description here http://docs.unity3d.com/ScriptReference/WWW.html I can inspect the isDone property, but in the example on the same page, it makes no attempt to inspect isDone.

我的问题是,如果我拨打WWW电话并且需要几秒钟的回复,游戏不会冻结吗?

The question I have is, if I make a WWW call and it takes several seconds to reply, doesn't the game freeze?

我想这是正确的代码,但是是吗?

I would like to think the right code is this, but is it?

StartCoroutine(WaitForResponse(myWWWObject));

private IEnumerator WaitForResponse(WWW aRequest ) {

    while ( ! aRequest.isDone )
        yield return aRequest;

}

游戏是否会冻结直到完成aRequest?还是真的是异步的?

Does the game freeze until aRequest is done? Or is it truly asynchronous?

推荐答案

您需要了解协程-这是Unity的一项基本功能,可让您编写持续时间较长的代码功能(例如:长于一帧) >不冻结游戏.

You need to understand Coroutines - a fundamental feature of Unity that allows you to write long-duration code functions (eg: longer then a frame) that will not freeze your game.

http://docs.unity3d.com/Manual/Coroutines.html

在C#中,您可以发现协程函数,因为它的返回类型为IEnumerator.而且,您可以通过C#关键字yield在代码中找到该函数将挂起并继续运行的位置.

In C# you can spot a coroutine function because it has a return type of IEnumerator. And you can spot the locations in the code where the function will suspend and continue from again by the C# keyword yield.

每个MonoBehaviour类都可以管理协程,如果您用StartCoroutine()告诉它开始一个协程,那么MonoBehaviour将在每一帧(有时多于一次)调用协程,直到协程结束.

Each MonoBehaviour class can manage coroutines, and if you tell it to start one with StartCoroutine(), then MonoBehaviour will call the coroutine every frame (sometimes more then once) until the Coroutine reaches the end.

对于WWW类(支持协同例程),您只需调用以下代码即可:

For WWW class (which supports co-routines), all you need is to call this:

  WWW www = new WWW(url);
  yield return www;

您创建了一个带有要检索的URL的WWW类,MonoDevelop协程管理器基本上会自动调用每一帧的产量,直到www对象说完成为止(成功或失败).

You create a WWW class with the URL to retrievve, and the yield will basically be called each frame automatically by the MonoDevelop coroutine manager until www object says it has completed (successfully or failure).

您的游戏在此期间完全不会冻结.

Your game will not freeze at all during this time.

这篇关于在Unity中,WWW类是异步的还是同步的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆