【案例】Unity 平台访问文件浏览器(汇总)

开发平台:Unity 2020

编程平台:Visual Studio 2022

使用 UnityEditor.EditorUtility.OpenFilePanel


使用背景:仅限制在编辑器模式下可用。无法参与发布项目中调用。

csharp 复制代码
public void ReadFile<T>()
{
	var thisFile = Selection.activeObject as T;
	if(thisFile != null)
	{
		var thisFilePath = EditorUtility.OpenFilePanel("标题", "打开目录路径", ".*", false);
		if(string.isNullOrEmpty(thisFilePath))
		{
			var thisFileBytes = File.ReadAllBytes(thisFilePath);
			thisFile.LoadImage(fileContent);
		}
	}
}

核心方法

复制代码
UnityEditor.EditorUtility.OpenFilePanel(string title, string directory, string extension, bool multiselect)

附注: directory=string.Empty:指向 Asset 目录路径

使用 System.Windows.Forms.OpenFileDialog


如果期望于发布项目中调用文件对话窗,则需要引入 System.Windows.Forms.dll 程序集至 plugin 目录中。

csharp 复制代码
public static bool OpenFile(string rootPath = UnityEngine.Application.dataPath, out string filePath)
{
	if (string.IsNullOrEmpty(rootPath))
	{
		filePath = string.empty;
		return false;
	}
	
	OpenFileDialog openFileDialog = new OpenFileDialog
	{
    	Title = "选择文件",                                      // 对话框标题
    	InitialDirectory = @"C:\\",                             // 初始目录
    	Filter = "文本文件 (*.txt)|*.txt|所有文件 (*.*)|*.*",    // 文件过滤器
    	FilterIndex = 2,                                       // 默认过滤器索引
    	RestoreDirectory = true,                               // 是否恢复之前的目录
    	Multiselect = false                                    // 是否允许多选
	};
	
	bool isOk = thisDialog.ShowDialog().OK;
	filePath =  isOk ?
		thisDialog.FileName : string.Empty;
	return isOk;
}
相关推荐
future_studio2 天前
聊聊 Unity(小白专享、C# 小程序 之 自动更新)
unity·小程序·c#
心疼你的一切2 天前
Unity开发利器:ScriptableObject的数据容器设计与内存优化原理
microsoft·unity·c#·游戏引擎
Cool-浩2 天前
【征文计划】Rokid 语音指令开发教程 【包含工程源码 和体验包APK】
unity·ar·语音识别·rokid·语音指令
小剑修2 天前
2025.10.18 复习
unity
future_studio4 天前
聊聊 Unity(小白专享、C# 小程序 之 播放器)
unity·小程序·c#
向宇it4 天前
【unity实战】MapMagic 2实战例子
游戏·3d·unity·c#·游戏引擎
SlowFeather4 天前
Unity TMP可控角度多色渐变文字
unity·游戏引擎
霜绛4 天前
Unity:UGUI笔记(一)——三大基础控件、组合控件
笔记·学习·unity·游戏引擎
小趴菜82275 天前
Android中加载unity aar包实现方案
android·unity·游戏引擎