C# 如果Unity3d中发生超时,请处理WWW
如果发生超时,我将尝试处理WWW对象。我正在使用以下代码:C# 如果Unity3d中发生超时,请处理WWW,c#,unity3d,coroutine,C#,Unity3d,Coroutine,如果发生超时,我将尝试处理WWW对象。我正在使用以下代码: WWW localWWW; void Start () { stattTime = Time.time; nextChange = Time.time + rotationSpeed; StartCoroutine ("DownloadFile"); } bool isStopped = false; bool isDownloadStarted = false; // Update is called
WWW localWWW;
void Start ()
{
stattTime = Time.time;
nextChange = Time.time + rotationSpeed;
StartCoroutine ("DownloadFile");
}
bool isStopped = false;
bool isDownloadStarted = false;
// Update is called once per frame
void Update ()
{ //2.0f as to simulate timeout
if (Time.time > stattTime + 2.0f && !isStopped) {
isStopped = true;
isDownloadStarted = false;
Debug.Log ("Downloading stopped");
StopCoroutine ("DownloadFile");
localWWW.Dispose ();
}
if (isDownloadStarted) {
}
if (Time.time > nextChange && isDownloadStarted) {
Debug.Log ("Current Progress: " + localWWW.progress);
nextChange = Time.time + rotationSpeed;
}
}
IEnumerator DownloadFile ()
{
isDownloadStarted = true;
GetWWW ();
Debug.Log ("Download started");
yield return (localWWW==null?null:localWWW);
Debug.Log ("Downlaod complete");
if (localWWW != null) {
if (string.IsNullOrEmpty (localWWW.error)) {
Debug.Log (localWWW.data);
}
}
}
public void GetWWW ()
{
localWWW = new WWW (@"http://www.sample.com");
}
但我有个例外:
NullReferenceException:已释放WWW类。
TestScript+c__迭代器2.MoveNext
我不确定我在这里做错了什么
有人能帮我吗?使用“使用”而不是手动处理,因为它会自动处理:
using ( WWW www = new WWW( url, form ) ) {
yield return www;
// check for errors
if ( www.error == null ) {
Debug.LogWarning( "WWW Ok: " + www.text );
} else {
Debug.LogWarning( "WWW Error: " + www.error );
}
}
使用“使用”而不是手动处置,因为它会自动处置:
using ( WWW www = new WWW( url, form ) ) {
yield return www;
// check for errors
if ( www.error == null ) {
Debug.LogWarning( "WWW Ok: " + www.text );
} else {
Debug.LogWarning( "WWW Error: " + www.error );
}
}
localWWW永远不应该为null,因为GetWWW总是返回一个新实例
下面的片段虽然难看,但应该可以让您开始
float elapsedTime = 0.0f;
float waitTime = 2.5f;
bool isDownloading = false;
WWW theWWW = null;
void Update () {
elapsedTime += Time.deltaTime;
if(elapsedTime >= waitTime && isDownloading){
StopCoroutine("Download");
theWWW.Dispose();
}
}
IEnumerator Download(string url){
elapsedTime = 0.0f;
isDownloading = true;
theWWW = new WWW(url);
yield return theWWW;
Debug.Log("Download finished");
}
localWWW永远不应该为null,因为GetWWW总是返回一个新实例
下面的片段虽然难看,但应该可以让您开始
float elapsedTime = 0.0f;
float waitTime = 2.5f;
bool isDownloading = false;
WWW theWWW = null;
void Update () {
elapsedTime += Time.deltaTime;
if(elapsedTime >= waitTime && isDownloading){
StopCoroutine("Download");
theWWW.Dispose();
}
}
IEnumerator Download(string url){
elapsedTime = 0.0f;
isDownloading = true;
theWWW = new WWW(url);
yield return theWWW;
Debug.Log("Download finished");
}
为什么会被否决?这是使用IDisposables的正确方法。为什么会被否决?这是使用IDisPobles的正确方法。