UnityWebRequest 加载网络图片当作贴图给物体

一、用UnityWebRequest加载网络图片并且当作Sprite给Image和贴图给3D物体

二、代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;

public class UNityWebTest : MonoBehaviour
{
    string url = @"http://pic37.nipic.com/20140113/8800276_184927469000_2.png";

    void Start()
    {
        StartCoroutine(DownSprite());
        StartCoroutine(DownMaterial());
    }

    IEnumerator DownSprite()
    {
        UnityWebRequest wr = new UnityWebRequest(url);
        DownloadHandlerTexture texDl = new DownloadHandlerTexture(true);
        wr.downloadHandler = texDl;
        yield return wr.SendWebRequest();
        int width = 1920;
        int high = 1080;
        if (!wr.isNetworkError)
        {
            Texture2D tex = new Texture2D(width, high);
            tex = texDl.texture;
            Sprite sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f));
            transform.GetComponent().sprite = sprite;
        }
    }
    IEnumerator DownMaterial()
    {
        UnityWebRequest wr = new UnityWebRequest(url);
        DownloadHandlerTexture texDl = new DownloadHandlerTexture(true);
        wr.downloadHandler = texDl;
        yield return wr.SendWebRequest();
        if (!wr.isNetworkError)
        {
            Texture2D tex = null;
            tex = texDl.texture;
            GameObject.Find("Cube").GetComponent().material.mainTexture = tex;
        }
    }

    private void OnApplicationQuit()
    {
        StopAllCoroutines();
    }
}

QQ交流群: 319506028

微信公众号 会定期推送一些资源
UnityWebRequest 加载网络图片当作贴图给物体_第1张图片

你可能感兴趣的:(Unity,Unity)