Unity 下載網(wǎng)絡(luò)圖片的方法,可使用WWW類或UnityWebRequest類,其中UnityWebRequest是新版的方法。
通常我們下載圖片都會轉(zhuǎn)成Texture,然后賦值給UI或者物體。
具體實現(xiàn)方法:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
public class LoadNetImage : MonoBehaviour
{
private string imagePath1 = "http://photocq.photo.store.qq.com/psc?/V12I366i33niTT/D58JeCw1McT8yUSxC9nwTKkKt7uD3ggcCPwGHf.kCG4HUdicWJ9EQ5ouDbp5F*R9DRS1hvwirV1qrJZO1AOKFA!!/b&bo=qgFAAQAAAAABF9o!&rf=viewer_4"; // 網(wǎng)絡(luò)圖片的路徑
public Renderer render1; //Plan對象1
public Renderer render2; //Plan對象2
public RawImage image1; //圖片對象1
public RawImage image2; //圖片對象2
// Start is called before the first frame update
void Start()
{
StartCoroutine(LoadTextureFromNet1(imagePath1));
StartCoroutine(LoadTextureFromNet2(imagePath1));
}
// Update is called once per frame
void Update()
{
}
//方法1
IEnumerator LoadTextureFromNet1(string filePath)
{
// 創(chuàng)建一個WWW對象并加載本地圖片
WWW www = new WWW(filePath);
yield return www;
if (string.IsNullOrEmpty(www.error))
{
// 獲取加載的紋理
Texture2D texture = www.texture;
//把貼圖賦到RawImage
image1.texture = texture;
//把貼圖賦到物體
Material material = new Material(Shader.Find("Standard"));
material.mainTexture = texture;
render1.material = material;
}
else
{
Debug.LogError("下載失?。? + www.error);
}
}
//方法2
IEnumerator LoadTextureFromNet2(string filePath)
{
// 創(chuàng)建一個UnityWebRequest對象并加載本地圖片
UnityWebRequest www = UnityWebRequestTexture.GetTexture(filePath);
yield return www.SendWebRequest();
if (www.result == UnityWebRequest.Result.Success)
{
// 獲取加載的紋理
Texture2D texture = DownloadHandlerTexture.GetContent(www);
//把貼圖賦到RawImage
image2.texture = texture;
//把貼圖賦到物體
Material material = new Material(Shader.Find("Standard"));
material.mainTexture = texture;
render2.material = material;
}
else
{
Debug.LogError("下載失敗:" + www.error);
}
}
}
使用上面方法,運行前:
運行后:
文章來源:http://www.zghlxwxcb.cn/news/detail-762422.html
完美把網(wǎng)絡(luò)圖片Load下來,并賦到UI和物體上。文章來源地址http://www.zghlxwxcb.cn/news/detail-762422.html
到了這里,關(guān)于Unity 下載網(wǎng)絡(luò)圖片的方法,并把圖片賦值給UI和物體的方法的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!