我先亮出我用的有关协程的代码:
using UnityEngine;
using System.Collections;
public class NewBehaviourScript : MonoBehaviour {
//本地图片的纹理
private Texture tex0;
//网络图片的纹理
private Texture tex1;
//加载本地图片
IEnumerator loadLocal()
{
if (tex0 == null) {
WWW date = new WWW("file://" + Application.dataPath + "/0.png");
yield return null;
tex0 = date.texture;
}
GetComponent<Renderer> ().material.mainTexture = tex0;
}
//加载网络图片
IEnumerator loadNetWork()
{
if (tex1 == null)
{
WWW date = new WWW ("http://pic39.nipic.com/20140321/17561764_000020626150_2.jpg");
while (!date.isDone)
{
yield return null;
Debug.Log ("时间:" + Time.time + " " + "进度:" + date.progress);
}
tex1 = date.texture;
}
GetComponent<Renderer> ().material.mainTexture = tex1;
}
void OnGUI()
{
if (GUILayout.Button ("load local pic")) {
StartCoroutine (loadLocal ());
}
if (GUILayout.Button ("load net pic")) {
StartCoroutine (loadNetWork());
}
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
如上所示,我的目的是通过点击Button本别加载本地图片与网络图片到Panel上。
既然是加载,那么加载就需要耗费时间,于是这里使用了协程,以保证图片加载完成后,再把图片赋值给mainTexture;
第一步:
在Button的响应中使用
StartCoroutine(loadNetWork())启动一个协程程序.
关于StartCoroutine
1.这个函数的参数,必须是一个返回值为IEnumerator类型的函数。
2.StartCoroutine不是启动了一个新的线程,而是开启一个协同程序,默认unity所有代码都在一个线程中
第二部:
执行loadNetWork函数
IEnumerator loadNetWork()
{
if (tex1 == null)
{
WWW date = new WWW ("http://pic39.nipic.com/20140321/17561764_000020626150_2.jpg");
/*while (!date.isDone)
{
yield return null;
Debug.Log ("时间:" + Time.time + " " + "进度:" + date.progress);
}*/
yield return date;
tex1 = date.texture;
}
GetComponent<Renderer> ().material.mainTexture = tex1;
}
我通过每句加输出语句观察到的现象是,程序执行完yield return date,之后停住了!,然后去执行了主程序中的下面的程序,然后接着执行了tex1 = date.texture;然后图片就显示出来了。我觉得好神奇,做了如下实验:
我把网断了,然后我发现程序在执行完yield return date后,很长时间没有反应,然后弹出了错误,说的是网络有问题访问不到之类的。
我把yield return date, 改成了yield retu