【Unity】WWW 和UnityWebRequest网络请求

     分别用WWW和UnityWebRequest 加载网络图片
/** 
 *Copyright(C) 2017 by MMHD 
 *All rights reserved. 
 *FileName:      LoadPic.cs 
 *Author:        Joel
 *Date:          2018/1/18
 *Description:    
 *History: By_307035570
*/  
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;

public class LoadPic : MonoBehaviour {

    public string url = "http://www.manew.com/template/manew2016/images/logo.png";
    void Awake()
    {
        //www加载网络图片更新至按钮
        //StartCoroutine(Load(url));

        // UnityWebRequestThe 加载
        //StartCoroutine(GetText());
    }


    IEnumerator Start()
    {
        using (WWW www = new WWW(url))
        {
            yield return www;
            //Renderer renderer =transform.GetComponent();
            //renderer.material.mainTexture = www.texture;
            Texture2D tex = new Texture2D(152, 50);
            www.LoadImageIntoTexture(tex);
            Sprite sprite = Sprite.Create(tex, new Rect(0, 0, 152, 50), Vector2.zero);
            transform.GetComponent().sprite = sprite;
        }
    }

    /// 
    /// UnityWebRequestThe 网络请求获取
    /// 
    /// 
    IEnumerator GetText()
    {
        using (UnityWebRequest www = UnityWebRequest.Get(url))
        {
            yield return www.Send();
            if (www.isError)
            {
                Debug.Log(www.error);
            }
            else
            {
                int width = 1920;
                int height = 1080;
                byte[] results = www.downloadHandler.data;
                Texture2D texture = new Texture2D(width, height);
                texture.LoadImage(results);
                yield return new WaitForSeconds(0.01f);
                Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
                transform.GetComponent().sprite = sprite;
                yield return new WaitForSeconds(0.01f);
                Resources.UnloadUnusedAssets();
            }
        }
    }

    /// 
    /// www 网络加载图片更新至按钮
    /// 
    /// 
    /// 
    IEnumerator Load(string path)
    {
        WWW www = new WWW(path);
        yield return www;
        if (!string.IsNullOrEmpty(www.error))
        {
            Debug.Log(www.error);
        }
        else
        {
            if (www.isDone)
            {
                Texture2D tex = new Texture2D(152,50);
                www.LoadImageIntoTexture(tex);
                Sprite sprite = Sprite.Create(tex, new Rect(0, 0, 152,50), Vector2.zero);
                GameObject btngo = GameObject.Find("Button");
                if (btngo)
                {
                    btngo.GetComponent().sprite = sprite;
                }
            }
        }
    }
}

你可能感兴趣的:(Unity)