环境
在更新Unity的插件时,如果插件里包含了plugings信息的时候,是需要关闭掉Unity才能升级的。因为一打开Unity,plugings就已经加载到主线程里面,不可能卸掉了,除非关掉Unity。这时候,就需要重启Unity的功能了。
测试过,在bat脚本关掉Unity的情况下,被Unity启动的cmd会被删掉。而Unity打开cmd后,自己关闭的话就不会关掉。
脚本
编辑器代码
using System.Diagnostics;
using UnityEngine;
using UnityEditor;
public class openTest
{
private string m_BatPath;
private string m_UnityPath;
private string m_ProjectPath;
private string m_AssetPath;
[MenuItem("Test/OpenDomain")]
private static void Open()
{
openTest demo = new openTest();
demo.InitData();
}
private void InitData()
{
m_UnityPath = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
m_AssetPath = Application.dataPath + "/..";
m_BatPath = Application.dataPath + "/openTest/UpdateFramework.bat";
int processId = Process.GetCurrentProcess().Id;
CreateProcess(m_BatPath, string.Format("\"{0}\" \"{1}\" ", m_UnityPath, m_AssetPath, m_UnityPath.Length);
Process.GetCurrentProcess().Kill();
}
//创建cmd
public Process CreateProcess(string cmd, string args, string workingDir = "")
{
var pStartInfo = new System.Diagnostics.ProcessStartInfo(cmd);
pStartInfo.Arguments = args;
pStartInfo.CreateNoWindow = false;
pStartInfo.UseShellExecute = true;
pStartInfo.RedirectStandardError = false;
pStartInfo.RedirectStandardInput = false;
pStartInfo.RedirectStandardOutput = false;
if (!string.IsNullOrEmpty(workingDir))
{
pStartInfo.WorkingDirectory = workingDir;
}
return System.Diagnostics.Process.Start(pStartInfo);
}
}
bat脚本
@echo off
set unityPath=%1%
set projectPath=%2%
for /f "delims="" tokens=1" %%v in ( %unityPath% ) do ( set unityPath=%%v )
for /f "delims="" tokens=1" %%v in ( %projectPath% ) do ( set projectPath=%%v )
start %unityPath% -projectPath %projectPath%
pause
技术点
- 输入路径的时候都加上“”双引号,在Window的情况下需要解析一下,mac不需要。加上双引号的原因是路径有可能有空格,一旦有空格就会被分割导致无法正确解析。
- 在脚本中使用ProcessStartInfo去创建process,起始路径是“项目路径/Assets”,不是脚本所在的路径。这一点很重要。要不就使用绝对路径,不然相对路径的问题要看清楚。参数WorkingDirectory就是设置这个起始路径。