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和物体上。

原文地址:https://blog.csdn.net/mr_five55/article/details/134758757

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_28572.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注