如果Unity3d中发生超时,则处理WWW
本文关键字:处理 WWW 超时 Unity3d 如果 | 更新日期: 2023-09-27 18:28:23
如果发生超时,我将尝试处理WWW对象。我正在使用以下代码:
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__Iterator2.MoveNext()
我不确定我在这里做错了什么。
有人能帮我吗?
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");
}
在自动处置时使用"using"而不是手动处置:
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 );
}
}
";使用";在C#中