【案例】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;
}
相关推荐
我的offer在哪里17 小时前
示例 Unity 项目结构(Playable Game Template)
unity·游戏引擎
淡海水20 小时前
【节点】[Branch节点]原理解析与实际应用
unity·游戏引擎·shadergraph·图形·branch
在路上看风景20 小时前
4.6 显存和缓存
unity
Zik----1 天前
简单的Unity漫游场景搭建
unity·游戏引擎
在路上看风景1 天前
4.5 顶点和片元
unity
在路上看风景2 天前
31. Unity 异步加载的底层细节
unity
天人合一peng2 天前
Unity中做表头时像work中整个调整宽窄
unity
小李也疯狂2 天前
Unity 中的立方体贴图(Cubemaps)
unity·游戏引擎·贴图·cubemap
牛掰是怎么形成的2 天前
Unity材质贴图引用陷阱:包体暴涨真相
unity·材质·贴图
呆呆敲代码的小Y2 天前
【Unity工具篇】| 超实用工具LuBan,快速上手使用
游戏·unity·游戏引擎·unity插件·luban·免费游戏·游戏配置表