通过网络链接加载图片作为image贴图
完整代码
using System;
using System.Collections;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
public class LoadTexture : MonoBehaviour
{
[Header("图片地址")]
[SerializeField]
private string url = "https://img-blog.csdnimg.cn/20200114151229684.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTAyMzMyOA==,size_16,color_FFFFFF,t_70";
// Use this for initialization
void Start()
{
StartCoroutine(DownSprite());
}
IEnumerator DownSprite()
{
UnityWebRequest wr = new UnityWebRequest(url);
DownloadHandlerTexture texD1 = new DownloadHandlerTexture(true);
wr.downloadHandler = texD1;
yield return wr.SendWebRequest();
int width = 1920;
int high = 1080;
if (!wr.isNetworkError)
{
Texture2D tex = new Texture2D(width, high);
tex = texD1.texture;
//保存本地
Byte[] bytes = tex.EncodeToPNG();
File.WriteAllBytes(Application.dataPath + "/02.png", bytes);
Sprite sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f));
transform.GetComponent<Image>().sprite = sprite;
}
}
private void OnApplicationQuit()
{
StopAllCoroutines();
}
}
该脚本挂在image身上运行即可
成功
原文链接:https://blog.csdn.net/weixin_42540271/article/details/95337041