Unity 中使用 UnityWebRequest 加载 StreamingAssets 文件夹中的图片

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录


一、先检查【打包输出文件夹】(最重要!)

打开你 WebGL 打包出来的目录,看里面有没有:

复制代码
打包输出文件夹
├ StreamingAssets   ✅ 这个文件夹必须存在!
│  └ myimg.png      ✅ 文件必须在这里!

二、完整代码(协程,RawImage,WebGL / 编辑器 / Windows 通用)

代码如下(示例):

c 复制代码
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
using System.Collections;
using System.IO;

public class LoadStreamingAssetsImg : MonoBehaviour
{
    public RawImage rawImage;
    // 图片在StreamingAssets里面的相对路径
     string imgName = "myimg.jpg";
    public Button button;
    private void Start()
    {
        button.onClick.AddListener(() => {
            AudioManager.Instance.PlayShoot(0);
            UICover.Instance.SetState(true);
            Destroy(this.gameObject);
        });
        StartCoroutine(LoadImg());
    }
   
    IEnumerator LoadImg()
    {
        // WebGL下 streamingAssetsPath 是 http 地址开头,直接拼接
        string filePath = Path.Combine(Application.streamingAssetsPath, imgName);
        Debug.Log("加载地址:" + filePath);

        using (var req = UnityWebRequestTexture.GetTexture(filePath))
        {
            yield return req.SendWebRequest();

            if (req.result == UnityWebRequest.Result.Success)
            {
                // 销毁旧贴图防内存泄漏
                if (rawImage.texture != null)
                {
                    Destroy(rawImage.texture);
                }
                Texture2D tex = DownloadHandlerTexture.GetContent(req);
                rawImage.texture = tex;
               // rawImage.SetNativeSize();
            }
            else
            {
                Debug.LogError("加载失败:" + req.error + " | url:" + filePath);
            }
        }
    }
}

如果是 Image(Sprite)版本

下面展示一些 内联代码片。

复制代码
Texture2D tex = DownloadHandlerTexture.GetContent(uwr);
Sprite sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f));
GetComponent<Image>().sprite = sprite;

总结

Player Settings → WebGL → Compression Format = Disabled(本地测试首选;Gzip 需要服务器配置 MIME 头,本地测试容易 404)

相关推荐
暴走约伯1 天前
【VFX工具链源码拆解 09】终极工业化闭环:基于 ID 规则驱动的全自动场景建档、骨骼挂载与男转女场景迁移
unity·c#·游戏引擎·材质
寂寞的船2 天前
【Unity知识速递】第13期 Unity 内存泄漏排查实战:从 Memory Profiler 到 Lua 引用泄漏的生产级全链路诊断
unity·junit·c#·游戏引擎·lua
寂寞的船3 天前
【Unity Bug挑战】第12期 Awaitable 二次 await 死锁之谜 —— 为什么同一个异步操作等两次就卡死?
unity·c#·游戏引擎·bug
探求虚无4 天前
用 AI 在 Unity 里做一款 RTS:最难的不是生成代码,而是证明它真的能玩
人工智能·unity·游戏引擎
17岁的勇气5 天前
Unity Shader unity文档学习笔记(二十二):shader变体
笔记·学习·unity
寂寞的船6 天前
【Unity知识速递】第10期 Unity GC 零分配实战:从 UnityEngine.Pool 到手动 GC 控制的全链路优化
jvm·unity·c#·游戏引擎·lucene
Martina_03217 天前
AI生成3D场景的霓虹灯一开就糊成光团?用6步检查Emissive、Bloom与曝光
人工智能·3d·ai·自然语言处理·游戏引擎·材质·贴图
寂寞的船8 天前
【Unity知识速递】第8期 IL2CPP 托管堆内存碎片与原生堆交互机制深度解析
unity·游戏引擎·交互
寂寞的船9 天前
【Unity知识速递】第5期 Unity 6.2 深度解析:AI Assistant 登场,World Space UI 与 Sentis 全面升级
人工智能·ui·unity
寂寞的船9 天前
【Unity知识速递】第4期 MCP for Unity:用 AI 自然语言控制编辑器
人工智能·unity·编辑器