欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Unity加载网络图片的两种方式

程序员文章站 2022-04-03 08:36:18
...
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;

/*
 * 
 *  Writer:June
 * 
 *  Date: 2020.12.26
 * 
 *  Function:两种从网络上下载图片的请求方式
 * 
 *  Remarks:这些方法仅支持Image组件
 * 
 */


public class RequestData : MonoBehaviour
{
    /// <summary>
    /// www请求
    /// </summary>
    /// <param name="_imageComp">image组件</param>
    /// <param name="_url">URL</param>
    public void GetImageByWWW(Image _imageComp, string _url)
    {
        StartCoroutine(WWWGetData(_imageComp, _url));
    }

    /// <summary>
    /// UnityWebRequest请求
    /// </summary>
    /// <param name="_imageComp">image组件</param>
    /// <param name="_url">URL</param>
    public void GetImageByUnityWebRequest(Image _imageComp, string _url)
    {
        StartCoroutine(UnityWebRequestGetData(_imageComp, _url));
    }


    IEnumerator WWWGetData(Image _imageComp, string _url)
    {
        using (WWW www = new WWW(_url))
        {
            yield return www;
            if (!string.IsNullOrEmpty(www.error)) Debug.Log(www.error);
            else
            {
                if (www.isDone)
                {
                    int width = 1920;
                    int height = 1080;
                    Texture2D texture2d = new Texture2D(width, height);
                    www.LoadImageIntoTexture(texture2d);
                    Sprite tempSprite = Sprite.Create(texture2d, new Rect(0, 0, width, height), new Vector2(0.5f, 0.5f));
                    _imageComp.sprite = tempSprite;
                }
            }
        }
    }


    IEnumerator UnityWebRequestGetData(Image _imageComp, string _url)
    {
        using (UnityWebRequest uwr = UnityWebRequestTexture.GetTexture(_url)) 
        {
            yield return uwr.SendWebRequest();
            if (uwr.isHttpError || uwr.isNetworkError) Debug.Log(uwr.error);
            else
            {
                if (uwr.isDone)
                {
                    int width = 1920;
                    int height = 1080;
                    Texture2D texture2d = new Texture2D(width, height);
                    texture2d = DownloadHandlerTexture.GetContent(uwr);
                    Sprite tempSprite = Sprite.Create(texture2d, new Rect(0, 0, width, height), new Vector2(0.5f, 0.5f));
                    _imageComp.sprite = tempSprite;
                    Resources.UnloadUnusedAssets();
                }
            }
        }
    }
}

 

相关标签: 笔记 unity3d