unity实现打开文件夹选择图片的两种方式:
一、引用System.Windows.Forms
此方法需要在unity的安装目录中找到System.Windows.Forms.dll文件并放在项目的Plugins文件夹中。注意:此方法在打包webgl版本时会报错。
using System.IO;
using System.Windows.Forms;public void CreatChartImgPanel()
{
OpenFileDialog od = new OpenFileDialog();
od.Title = "请选择图片";
od.Multiselect = false;
od.Filter = "图片文件(*.jpg,*.png,*.bmp)|*.jpg;*.png;*.bmp";if (od.ShowDialog() == DialogResult.OK)
string TexPath = od.FileName;if (!File.Exists(TexPath))
{
Debug.Log("加载失败");
return;
}//WWW方式加载图片
StartCoroutine(WWW_Tex("file://" + TexPath));
}
二、引用System.Runtime.InteropServices
此方法PC、webgl均可使用
using System.IO;
using System.Runtime.InteropServices;
public void CreatChartImgPanel()
{OpenFileName ofn = new OpenFileName();
ofn.structSize = Marshal.SizeOf(ofn);
ofn.filter = "All Files\0*.*\0\0";
ofn.file = new string(new char[256]);
ofn.maxFile = ofn.file.Length;
ofn.fileTitle = new string(new char[64]);
ofn.maxFileTitle = ofn.fileTitle.Length;
string path = Application.streamingAssetsPath;
path = path.Replace('/', '\\');
ofn.initialDir = path;
ofn.title = "Open Project";
ofn.defExt = "JPG";
//注意 一下项目不一定要全选 但是0x00000008项不要缺少
ofn.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000200 | 0x00000008;
if (WindowDll.GetOpenFileName(ofn))
{
Debug.Log("Selected file with full path:" + ofn.file);
}
if (ofn.file != "")
{
StartCoroutine(WWW_Tex(ofn.file));
}
}
选择完然后加载本地图片
Texture wwwTexture;
IEnumerator WWW_Tex(string url)
{
WWW www = new WWW(url);
yield return www;
if (www.isDone && www.error == null)
{
wwwTexture = www.texture;
}
}