【案例】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;
}
相关推荐
心疼你的一切2 小时前
Unity异步编程神器:Unitask库深度解析(功能+实战案例+API全指南)
深度学习·unity·c#·游戏引擎·unitask
呆呆敲代码的小Y4 小时前
【Unity 实用工具篇】 | Book Page Curl 快速实现翻书效果
游戏·unity·游戏引擎·u3d·免费游戏·翻书插件
AC梦17 小时前
unity中如何将UI上的字高清显示
ui·unity
小贺儿开发1 天前
Unity3D 智慧城市管理平台
数据库·人工智能·unity·智慧城市·数据可视化
June bug2 天前
【领域知识】休闲游戏一次发版全流程:Google Play + Apple App Store
unity
星夜泊客2 天前
C# 基础:为什么类可以在静态方法中创建自己的实例?
开发语言·经验分享·笔记·unity·c#·游戏引擎
dzj20212 天前
PointerEnter、PointerExit、PointerDown、PointerUp——鼠标点击物体,则开始旋转,鼠标离开或者松开物体,则停止旋转
unity·pointerdown·pointerup
心前阳光2 天前
Unity 模拟父子关系
android·unity·游戏引擎
在路上看风景2 天前
26. Mipmap
unity
咸鱼永不翻身2 天前
Unity视频资源压缩详解
unity·游戏引擎·音视频