Unity3D启动外部程序并传递参数的实现

Shaine ·
更新时间:2024-09-20
· 1657 次阅读

之前开发项目,一直都使用的是外壳程序加子程序的模式,通过外壳程序去启动子程序,外壳程序和子程序之间的通信,是使用配置文件完成的。

我总觉得这样通信很麻烦,因为外壳程序需要对配置文件进行更改和写入,然后子程序又要读取信息。而且整合的时候,会导致有很多配置文件,而且需要对路径做很多处理和限制。

我发现Process.Start()函数中,是可以传递参数的。

也就是说,我们是可以在使用Process.Start()函数启动外部程序时,传递参数的进行通信的。

具体操作如下: public void StartEXE() { ProcessStartInfo processStartInfo = new ProcessStartInfo(); processStartInfo.FileName = "C:/Users/Administrator/Desktop/Test/Demo.exe"; processStartInfo.Arguments = "启动 程序 1 2 3"; Process.Start(processStartInfo); }

需要注意的是,如果存在多个参数的话,参数之间需要使用空格进行分隔。

外壳程序已经传递了参数,那么子程序如何接受参数呢?具体操作如下:

private void Start() { string[] args = Environment.GetCommandLineArgs(); text.text = args.Length.ToString(); for (int i = 0; i < args.Length; i++) { text.text += "\n" + "Arg" + i + ": " + args[i]; } }

我将所有的参数信息,打印在了一个Text上面。运行效果图如下:

补充:Unity3D:启动外部exe传参以及设置窗口位置和大小

好久没有更新博客了,最近项目上没有太大的突破,也没有涉及到新东西,所以想写博客,但是无奈没有新东西,好在最近有点新的功能要做,之前也做过,但是并没有整理成博客,现在就记录一下。省的还要去百度找。(最近好像新的Unity版本不能破解了,官网有时候也上不去,不知道Unity要搞什么东东。)

今天要说的是Unity启动外部exe,并且传递参数,改变外部exe窗口位置以及窗口大小。启动exe这个百度搜一大堆,主要是怎么设置窗口位置及大小。窗口大小的方法Unity有自己的方法,但是位置就没法设置了,我今天用的方法是Windows原生的方法。需要引用user32.dll。

废话不多说了,下面上代码 using UnityEngine; using System.Runtime.InteropServices; using System; using System.Diagnostics; public class ProperWindows : MonoBehaviour { [DllImport("user32.dll")] static extern IntPtr SetWindowLong(IntPtr hWnd, int _nIndex, int dwNewLong); [DllImport("user32.dll")] static extern bool SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags); [DllImport("user32.dll")] static extern IntPtr GetForegroundWindow(); //获取最前端窗体句柄 [DllImport("user32.dll")] static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); //[DllImport("user32.dll")] //static extern IntPtr GetWindowThreadProcessld(); private void Awake() { //启动时传过来的string数组,下标为0的是启动的外部exe程序的完整路径,下标为1及之后的参数是想要传过来的参数。 string[] args = Environment.GetCommandLineArgs(); var winInfo = JsonUtility.FromJson<WinInfo>(args[1]); // 设置屏大小和显示位置 SetWindowPos(GetForegroundWindow(), 0, winInfo.x, winInfo.y, winInfo.width, winInfo.height, 0x0040); } // Use this for initialization void Start() { //启动外部exe程序,第一个参数为exe完整路径,第二个参数为要传入的参数。 string winInfo = JsonUtility.ToJson(new WinInfo(0, 0, 1000, 500)); Process.Start(@"C:\Users\wangbo\Desktop\2\2.exe", winInfo); } // Update is called once per frame void Update() { } } [Serializable] public class WinInfo { public int x; public int y; public int width; public int height; public WinInfo(int x, int y, int width, int height) { this.x = x; this.y = y; this.width = width; this.height = height; } }

上面的代码里我传的参数是json格式的,在Start里启动一个exe,在Awake里接收参数,设置窗口位置以及大小。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持软件开发网。如有错误或未考虑完全的地方,望不吝赐教。



程序 参数 unity3d unity

需要 登录 后方可回复, 如果你还没有账号请 注册新账号