Unity打开外部文件夹并选择文件

最近需要做一个服务器一键开启客户端相同路径程序的功能,需要在服务器选择相应文件夹的程序,然后同时服务器客户度同时开启选中程序,首先需要从unity打开外部文件夹并选择文件的功能,具体操作如下:

首先创建一个单独的类,用来储存打开的系统窗口的设置,下面的变量没有特殊要求不需要做任何改动:

using UnityEngine;
using System.Collections;
using System;
using System.Runtime.InteropServices;

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public class OpenFileName
{
    public int structSize = 0;
    public IntPtr dlgOwner =IntPtr.Zero;
    public IntPtr instance = IntPtr.Zero;
    public String filter = null;
    public String customFilter = null;
    public int maxCustFilter = 0;
    public int filterIndex = 0;
    public String file = null;
    public int maxFile = 0;
    public String fileTitle = null;
    public int maxFileTitle = 0;
    public String initialDir = null;
    public String title = null;
    public int flags = 0;
    public short fileOffset = 0;
    public short fileExtension = 0;
    public String defExt = null;
    public IntPtr custData = IntPtr.Zero;
    public IntPtr hook = IntPtr.Zero;
    public String templateName = null;
    public IntPtr reservedPtr = IntPtr.Zero;
    public int reservedInt = 0;
    public int flagsEx = 0;


}

然后我们需要在创建一个类导入Window的链接库,代码也不需要做更改:

using System.Runtime.InteropServices;

public class LocalDialog
{
    //链接指定系统函数       打开文件对话框
    [DllImport("Comdlg32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]
    public static extern bool GetOpenFileName([In, Out] OpenFileName ofn);
    public static bool GetOFN([In, Out] OpenFileName ofn)
    {
        return GetOpenFileName(ofn);//执行打开文件的操作
    }

    //链接指定系统函数        另存为对话框
    [DllImport("Comdlg32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]
    public static extern bool GetSaveFileName([In, Out] OpenFileName ofn);
    public static bool GetSFN([In, Out] OpenFileName ofn)
    {
        return GetSaveFileName(ofn);//执行保存选中文件的操作
    }
}

完成上面两步就可以开始调用打开系统窗口选择文件的操作,我创建了一个类用来执行打开选择的方法,其中的打开文件夹方法如下:

 public void OpenDirectory(string type)
    {
        openFileName = new OpenFileName();
        openFileName.structSize = Marshal.SizeOf(openFileName);
        openFileName.filter = "文件(*." + type + ")\0*." + type + "";
        openFileName.file = new string(new char[256]);
        openFileName.maxFile = openFileName.file.Length;
        openFileName.fileTitle = new string(new char[64]);
        openFileName.maxFileTitle = openFileName.fileTitle.Length;
        openFileName.initialDir = Application.streamingAssetsPath.Replace('/', '\\');//默认路径
        openFileName.title = "选择文件";
        openFileName.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000008;

        if (LocalDialog.GetSaveFileName(openFileName))//点击系统对话框框保存按钮
        {
          //TODO

        }

在这个方法里面要注意:对openFileName这个类里面的变量赋值就是设置系统窗口的效果,其中可以更改的地方有:

  openFileName.title :表示打开的系统窗口名称

 openFileName.filter:这个表示需要选择的文件类型,书写格式就是上面的格式,类型按照需求填写,打开的窗口效果如下:

我填写的类型是exe,可以选择的类型就是exe文件,

openFileName.filter = "文件(*." + type + ")\0*." + type + ""; \后面的意思就是剔除其他非exe文件,例如我后面有一个选择图片的功能,格式就是:openFileName.filter = "文件(*.png;*.jpg)\0*.png;*.jpg";表示选择png和jpg格式的文件,其他格式文件不在窗口显示,多种格式的文件选择加;隔开。效果如下:

到了这一步就可以进行打开外部文件夹选择文件了,当我们点击保存按钮就会执行红框里面的方法,就可以按照需求编写功能

欢迎加群:4364930讨论。

<think>我们正在讨论Unity打开外部程序的方法。根据用户的问题和提供的引用,我们可以总结出几种实现方式。首先,引用[1]和引用[4]展示了使用`System.Diagnostics.Process`来启动外部程序。这是C#中标准的启动外部进程的方法,同样适用于Unity。引用[2]提到了在WebGL平台上通过`Application.ExternalCall`调用JavaScript函数来打开外部程序,因为WebGL环境有安全限制,不能直接启动本地程序。引用[3]则展示了在QML界面中嵌入Unity游戏,通过QProcess启动外部程序(这里是Unity游戏),然后通过设置窗口父子关系来嵌入窗口。引用[5]展示了打开一个Word文件,同样是使用`Process.Start`。因此,我们可以根据目标平台选择不同的方法:1.对于PC、Mac、Linux等桌面平台,可以直接使用`Process.Start`。2.对于WebGL平台,需要通过JavaScript桥接。3.如果需要在其他程序中嵌入Unity,或者将外部程序嵌入Unity,则可能需要使用窗口句柄操作(仅Windows)。现在,用户的问题是“在Unity打开外部程序的方法”,我们重点介绍通用的桌面平台方法,简要提及其他平台。###在Unity打开外部程序(桌面平台)1.**使用`System.Diagnostics.Process`类**:这是最直接的方法。以下是一个简单的示例:```csharpusingUnityEngine;usingSystem.Diagnostics;//引入命名空间publicclassOpenExternalProgram:MonoBehaviour{//外部程序的完整路径publicstringprogramPath;publicvoidOpenProgram(){//检查路径是否为空if(string.IsNullOrEmpty(programPath)){UnityEngine.Debug.LogError("程序路径为空!");return;}try{//启动外部程序Process.Start(programPath);UnityEngine.Debug.Log("程序启动成功");}catch(System.Exceptione){UnityEngine.Debug.LogError($"启动程序失败:{e.Message}");}}}```将上述脚本挂载到游戏对象上,在Inspector面板中设置`programPath`为外部程序的完整路径(如:`C:\\ProgramFiles\\Example\\example.exe`),然后调用`OpenProgram`方法(例如通过按钮点击事件)即可。2.**传递参数**:如果需要向外部程序传递参数,可以使用`ProcessStartInfo`类,如引用[4]所示:```csharppublicvoidOpenProgramWithArgs(){stringprogramPath="E:\\fastdds\\run\\PlanA.exe";stringarguments="param1param2";//参数ProcessStartInfostartInfo=newProcessStartInfo();startInfo.FileName=programPath;startInfo.Arguments=arguments;try{Process.Start(startInfo);}catch(System.Exceptione){UnityEngine.Debug.LogError(e.Message);}}```3.**WebGL平台**:由于浏览器安全限制,不能直接启动本地程序。需要调用JavaScript函数,然后由JavaScript尝试打开程序(通常通过自定义URL协议,或者下载链接等方式)。在Unity中,使用`Application.ExternalCall`调用页面上定义的JavaScript函数,如引用[2]所示:在UnityC#脚本中:```csharppublicvoidClickFunc_TestEXE(){Application.ExternalCall("btn_TestEXE");//调用页面上的JavaScript函数btn_TestEXE}```在HTML页面中,需要定义这个JavaScript函数:```html<script>functionbtn_TestEXE(){//尝试通过自定义协议打开应用程序,或者弹出下载window.location.href="myapp://open";//需要提前注册协议//或者使用其他方法,如ActiveX(仅IE)等}</script>```4.**嵌入外部程序窗口(仅Windows)**:如引用[3]和[4]所示,可以通过获取窗口句柄,外部程序窗口设置为Unity窗口的子窗口。但这种方法比较复杂,且仅适用于Windows平台。###注意事项-路径问题:在Unity中,路径需要使用双反斜杠`\\`或正斜杠`/`。-异常处理:启动外部程序可能会因为路径错误、权限不足等原因失败,务必添加异常处理。-跨平台:不同平台的可执行文件格式不同(Windows为.exe,macOS为.app,Linux可能无扩展名),需要根据平台选择不同的路径。-权限:在某些操作系统上,可能需要额外的权限才能启动外部程序。###示例:跨平台打开外部程序下面是一个跨平台的示例,根据运行平台选择不同的程序路径:```csharpusingUnityEngine;usingSystem.Diagnostics;usingSystem.Runtime.InteropServices;//用于DllImportpublicclassCrossPlatformOpen:MonoBehaviour{publicvoidOpenProgram(){stringprogramPath="";stringarguments="";//根据平台设置路径和参数if(Application.platform==RuntimePlatform.WindowsPlayer||Application.platform==RuntimePlatform.WindowsEditor){programPath="C:\\ProgramFiles\\MyApp\\myapp.exe";arguments="arg1arg2";}elseif(Application.platform==RuntimePlatform.OSXPlayer||Application.platform==RuntimePlatform.OSXEditor){programPath="/Applications/MyApp.app/Contents/MacOS/MyApp";arguments="arg1arg2";}elseif(Application.platform==RuntimePlatform.LinuxPlayer){programPath="/usr/bin/myapp";arguments="arg1arg2";}else{UnityEngine.Debug.LogError("Unsupportedplatform");return;}ProcessStartInfostartInfo=newProcessStartInfo();startInfo.FileName=programPath;startInfo.Arguments=arguments;try{Process.Start(startInfo);}catch(System.Exceptione){UnityEngine.Debug.LogError($"Failedtostartprocess:{e.Message}");}}}```###总结在Unity打开外部程序,最常用的方法是使用`Process.Start`(桌面平台)。对于WebGL平台,则需要通过JavaScript间接实现。此外,还可以通过窗口句柄操作将外部程序窗口嵌入Unity中,但这通常更复杂且平台相关。§§相关问题§§1.Unity如何打开外部程序传递参数?2.在UnityWebGL中如何打开外部程序?3.如何将外部程序的窗口嵌入到Unity中?4.Unity启动外部程序时如何避免安全风险?5.Unity启动外部程序后如何检测其关闭?</think>### Unity打开外部程序的方法 在Unity打开外部程序主要有以下几种方法,根据平台和需求选择合适的方式: #### 1. 使用`System.Diagnostics.Process`类(通用方法) ```csharp using UnityEngine; using System.Diagnostics; public class OpenExternalProgram : MonoBehaviour { // 方法1:直接启动程序 public void OpenProgram(string programPath) { try { Process.Start(programPath); // 启动外部程序 Debug.Log($"已启动: {programPath}"); } catch (System.Exception e) { Debug.LogError($"启动失败: {e.Message}"); } } // 方法2:带参数启动(如打开特定文件) public void OpenProgramWithArgs() { ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.FileName = "C:/Program Files/Example/example.exe"; // 程序路径 startInfo.Arguments = "param1 param2"; // 启动参数 Process.Start(startInfo); } } ``` **说明**: - 适用于Windows/Mac/Linux桌面平台 - 可指定完整路径或环境变量中的程序名 - 通过`Arguments`属性传递命令行参数[^5] #### 2. WebGL平台的特定方法 ```csharp // 需要配合JavaScript桥接 public void OpenInWebGL() { // 调用预定义的JS函数 Application.ExternalCall("window.openExternalApp"); } ``` **HTML端需要添加**: ```html <script> function window.openExternalApp() { // 通过自定义协议或下载链接打开 window.location.href = "myapp://open"; } </script> ``` **限制**: - 需要浏览器支持自定义协议或用户授权 - 无法直接启动本地可执行文件[^2] #### 3. 嵌入外部程序窗口(仅Windows) ```csharp // 获取窗口句柄嵌入Unity [DllImport("user32.dll")] private static extern IntPtr SetParent(IntPtr hwndChild, IntPtr hwndNewParent); public void EmbedProgramWindow() { Process proc = Process.Start("notepad.exe"); proc.WaitForInputIdle(); // 等待程序启动 // 设置Unity窗口为父窗口 IntPtr unityWindow = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle; SetParent(proc.MainWindowHandle, unityWindow); } ``` **说明**: - 使用Windows API的`SetParent`函数 - 需要等待程序完成初始化[^3][^4] - 仅适用于Windows桌面应用 #### 4. 打开关联文件 ```csharp // 用默认程序打开文件 public void OpenAssociatedFile(string filePath) { if(System.IO.File.Exists(filePath)) { Process.Start(filePath); // 系统自动调用关联程序 } } ``` **示例**: ```csharp OpenAssociatedFile("C:/Users/Desktop/report.pdf"); // 用PDF阅读器打开 OpenAssociatedFile("C:/data/data.xlsx"); // 用Excel打开 ``` ### 关键注意事项 1. **路径规范**: - Windows使用`C:/Path/Program.exe`(斜杠兼容) - 避免空格路径,必要时用引号包裹:`"C:/Program Files/app.exe"` 2. **平台兼容**: ```csharp #if UNITY_STANDALONE_WIN // Windows专用代码 #elif UNITY_WEBGL // WebGL专用代码 #endif ``` 3. **权限处理**: - 移动平台需要额外权限声明 - WebGL需用户交互触发(不能自动启动) 4. **错误处理**: - 使用`try-catch`捕获权限/路径错误 - 检查文件存在性:`System.IO.File.Exists()` > 提示:测试时建议从`Application.dataPath`获取安全路径(如`Application.dataPath + "/../external_app.exe"`)
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值