【案例】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;
}
相关推荐
真鬼12311 小时前
【Unity WebGL】内嵌网页与双向通信
unity·游戏引擎·webgl
zyh______19 小时前
C#语法糖(按照实用性排序)
unity·c#
avi911121 小时前
[AI教做人]CinemachineCamera 各项调整配置参数入门 + Profiler
unity·游戏开发·camera·cinemachine·visual camera·镜头配置
郝学胜-神的一滴2 天前
[简化版 GAMES 101] 计算机图形学 16:纹理走样、Mipmap、三线性插值、各向异性过滤原理全解
unity·游戏引擎·godot·图形渲染·three.js·opengl·unreal
吴梓穆3 天前
untiy TextMeshPro (TMP) text 操作 中文字符集 字体材质操作(添加纹理 添加描边 添加阴影)
unity
想你依然心痛3 天前
嵌入式单元测试:Unity/CMock框架与硬件在环测试——测试驱动、桩函数
unity·单元测试·游戏引擎
xcLeigh3 天前
Unity基础:Game视图详解——游戏预览、分辨率模拟与性能显示
游戏·unity·游戏引擎·音频·视频·game·play模式
xcLeigh3 天前
Unity基础:Scene视图操作完全指南——视角控制、物体选择与场景导航
unity·游戏引擎·scene·试图·场景导航
mxwin3 天前
Unity Shader exp 函数的算法与渲染应用
算法·unity·游戏引擎·shader
mxwin4 天前
Unity URP Exposure曝光原理与实战应用
unity·游戏引擎