Unity 下载网络图片的方法,并把图片赋值给UI和物体的方法

Unity 下载网络图片的方法,可使用WWW类或UnityWebRequest类,其中UnityWebRequest是新版的方法。

通常我们下载图片都会转成Texture,然后赋值给UI或者物体。

具体实现方法:

复制代码
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"; // 网络图片的路径    
    

    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)
    {
        // 创建一个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)
    {
        // 创建一个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);
        }
    }
}

使用上面方法,运行前:

运行后:

完美把网络图片Load下来,并赋到UI和物体上。

相关推荐
晴夏。1 小时前
UE原生MovementBase实现分析
游戏引擎·ue·3c
烟话61 小时前
C# 内存机制详解:值类型、引用类型与 String 的不可变性
java·jvm·c#
我是唐青枫2 小时前
C#.NET MemoryMarshal 深入解析:零拷贝内存重解释、二进制读写与使用边界
c#·.net
天人合一peng2 小时前
Unity工程发布hololens需安装, MRTK安装
unity·游戏引擎·hololens
susan花雨2 小时前
C#异步并行处理的用法
c#
weixin_409383123 小时前
godot 调用class方法得用实例 不能用脚本引用
游戏引擎·godot
风酥糖3 小时前
Godot游戏练习01-第32节-国际化
游戏·游戏引擎·godot
weixin_520649873 小时前
Winform创建与启动
开发语言·c#
武藤一雄3 小时前
WPF中逻辑树(Logical Tree)与可视化树(Visual Tree)到底是什么
microsoft·c#·.net·wpf·.netcore
周杰伦fans4 小时前
深入 C# 匿名类型:从 `new { Ask = ask }` 说起
开发语言·c#