协同程序的返回类型为Coroutine类型。在Unity3D中,Coroutine类继承于YieldInstruction,所以,协同程序的返回类型只能为null、等待的帧数(frame)以及等待的时间。
协同程序的参数不能指定ref、out参数。但是,我们在使用WWW类时会经常使用到协同程序,由于在协同程序中不能传递参数地址(引用),也不能输出对 象,这使得每下载一个WWW对象都得重写一个协同程序,解决这个问题的方法是建立一个基于WWW的类,并实现一个下载方法。如下:
usingUnityEngine;
usingSystem.Collections;
publicclassWWWObject:MonoBehaviour
{
public WWW www;
publicWWWObject(string url)
{
if(GameVar.wwwCache)
www =WWW.LoadFromCacheOrDownload(url,GameVar.version);
else
www =new WWW(url);
}
publicIEnumeratorLoad()
{
Debug.Log("Start loading : "+www.url);
while(!www.isDone)
{
if(GameVar.gameState
==GameState.Jumping||GameVar.gameState
==GameState.JumpingAsync)
LoadScene.progress
=www.progress;
yieldreturn1;
}
if(www.error!=null)
Debug.LogError("Loading error : "+www.url+"\n"+www.error);
else
Debug.Log("End loading : "+www.url);
}
publicIEnumeratorLoadWithTip(string resourcesName)
{
Debug.Log("Start loading : "+www.url);
LoadScene.tipStr
= "Downloading resources <"+ resourcesName
+"> . . .";
while(!www.isDone)
{
if(GameVar.gameState
==GameState.Jumping||GameVar.gameState
==GameState.JumpingAsync)
LoadScene.progress
=www.progress;
yieldreturn1;
}
if(www.error!=null)
Debug.LogError("Loading error : "+www.url+"\n"+www.error);
else
Debug.Log("End loading : "+www.url);
}
}
调用:
usingUnityEngine;
usingSystem.Collections;
usingSystem.Collections.Generic;
publicclassLoadResources:MonoBehaviour
{
staticstring url
="http://61.149.211.88/Package/test.unity3d";
publicstatic WWW www
=null;
IEnumeratorStart()
{
if(!GameVar.resourcesLoaded)
{
GameVar.gameState
=GameState.Jumping;
WWWObject obj
=newWWWObject(url);
www = obj.www;
yieldreturnStartCoroutine(obj.LoadWithTip("Textures"));
GameVar.resourcesLoaded
=true;
GameVar.gameState
=GameState.Run;
}
}
}
联系客服