如何通過網(wǎng)絡端下載一些資源命黔,看完下面的內(nèi)容,你會有所了解.
從網(wǎng)絡端獲取資源
在上面的操作過程中其實顯示的圖片是從網(wǎng)絡端獲得過來的.點擊了q鍵就會從網(wǎng)絡端加載這個圖片.
首先菜秦,我們了解一下協(xié)程吧!協(xié)程不是線程七咧,也不是異步執(zhí)行的吴超,在MainThread中執(zhí)行.控制代碼在特定的時候執(zhí)行.
協(xié)同程序可以和主程序并行運行,和多線程有點類似.協(xié)同程序可以用來實現(xiàn)讓一段程序等待一段時間后繼續(xù)運行的效果.
// Use this for initialization
void Start () {
print("789");
StartCoroutine(WorkHard());//在StartCoroutine方法中執(zhí)行助被。
print("101112");
}
// Update is called once per frame
void Update () {
}
IEnumerator WorkHard()//一個返回值為IEnumerator類型
{
print("123");
yield return new WaitForSeconds(2f);//用yield return返回
print("456");
}
動態(tài)圖的代碼演示.
Texture2D t2d;
public string Url;
WWW www;//這是一個類
// Use this for initialization
void Start () {
Url = "http://ww2.sinaimg.cn/mw240/005OPYkojw1etn14eqlj8j30go0m8ab3.jpg";//網(wǎng)絡上的圖片資源
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.Q))
{
StartCoroutine(GetWWW());
}
}
IEnumerator GetWWW()
{
www = new WWW(Url);
yield return www;
print("返回數(shù)據(jù)成功");
t2d = www.texture;//獲取圖片資源
}
private void OnGUI()
{
GUILayout.Label(Url);
GUILayout.TextArea(""+www);
GUILayout.Label(""+www);
GUI.DrawTexture(new Rect(100,100,100,100),t2d);//繪制圖片的位置和大小
}