You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity运行时(非编辑器模式)如何上传并加载图片/.txt文件?

Unity运行时实现文件选择与图片/TXT加载方案

一、运行时文件选择的核心实现

Unity自带的EditorUtility.OpenFilePanel仅在编辑器模式生效,运行时需要调用平台原生的文件选择对话框。以下是Windows平台的轻量实现,以及跨平台思路:

Windows平台(基于System.Windows.Forms)

  1. 配置项目:在Unity编辑器的Player Settings中,将Api Compatibility Level设置为.NET Framework(而非.NET Core)。
  2. 导入依赖:从Unity安装目录的Editor\Data\MonoBleedingEdge\lib\mono\4.7.2-api路径下,复制System.Windows.Forms.dll和System.Drawing.dll到项目的Plugins文件夹。
  3. 实现文件选择与加载代码:
using System.Windows.Forms;
using UnityEngine;
using System.IO;

public class RuntimeFileLoader : MonoBehaviour
{
    // 绑定到UI按钮的方法,触发文件选择
    public void TriggerFilePicker()
    {
        var openDialog = new OpenFileDialog();
        // 筛选可选择的文件类型
        openDialog.Filter = "图片文件 (*.png;*.jpg)|*.png;*.jpg|文本文件 (*.txt)|*.txt|所有文件 (*.*)|*.*";
        openDialog.RestoreDirectory = true;

        if (openDialog.ShowDialog() == DialogResult.OK)
        {
            var filePath = openDialog.FileName;
            var ext = Path.GetExtension(filePath).ToLower();

            switch (ext)
            {
                case ".png":
                case ".jpg":
                case ".jpeg":
                    LoadAndProcessImage(filePath);
                    break;
                case ".txt":
                    LoadAndProcessTxt(filePath);
                    break;
            }
        }
    }

    private void LoadAndProcessImage(string path)
    {
        var imageBytes = File.ReadAllBytes(path);
        var texture = new Texture2D(2, 2);
        texture.LoadImage(imageBytes);
        
        // 示例:将Texture赋值给RawImage显示
        // GetComponent<RawImage>().texture = texture;
        
        // 如需转为Sprite
        var sprite = Sprite.Create(texture, new Rect(0,0,texture.width,texture.height), new Vector2(0.5f,0.5f));
        Debug.Log($"图片加载完成:{texture.width}x{texture.height}");
    }

    private void LoadAndProcessTxt(string path)
    {
        // 处理中文乱码可指定编码,如Encoding.UTF8
        var content = File.ReadAllText(path);
        // 示例:显示到UI文本框
        // GetComponent<TMPro.TextMeshProUGUI>().text = content;
        Debug.Log($"TXT内容:\n{content}");
    }
}

跨平台方案

如果需要支持Mac/Linux,推荐使用Unity Asset Store中的原生文件选择插件(如Native File Picker),这类插件封装了各平台的原生对话框API,无需手动处理不同平台的代码差异。

二、你之前方法失效的原因

  • Application.OpenURL仅能打开外部链接或系统文件夹,无法捕获用户选中的文件路径,因此无法将文件内容导入Unity。
  • Process.Start("explorer.exe")只是启动资源管理器,同样无法获取用户的选择结果,仅能让用户手动浏览文件夹,无法完成文件到Unity的传递。

三、注意事项

  • 权限问题:打包后的程序避免安装到C盘Program Files等受系统权限限制的目录,否则可能无法读取文件。
  • 图片内存优化:加载大尺寸图片时,建议压缩纹理格式或调整分辨率,避免内存溢出。
  • 编码兼容:读取TXT文件时,若遇中文乱码,明确指定文件编码(如Encoding.UTF8或Encoding.Default)。

内容的提问来源于stack exchange,提问作者AgentBurger

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 21:01:44