当前位置:网站首页>Using the command line to call shell in unity
Using the command line to call shell in unity
2022-06-11 22:22:00 【KindSuper_ liu】
Unity Call in Shell The command line
Sometimes we do unity When developing, you need to write some tools, which are usually used outside the editor python, But sometimes it is also used shell Command line to complete some operations , For example, when we are writing an automated packaging I often use some linux Command to perform some operations on files or folders , At this time shell It's very practical. . So here's a shell Tool class to help us in unity For easier use in shell Some of the instructions for . c# The code is as follows :
using UnityEngine;
using System.Collections;
using System.Diagnostics;
using UnityEditor;
using System.Collections.Generic;
public class ShellHelper {
public class ShellRequest{
public event System.Action<int,string> onLog;
public event System.Action onError;
public event System.Action onDone;
public void Log(int type,string log){
if(onLog != null){
onLog(type,log);
}
if (type == 1) {
UnityEngine.Debug.LogError (log);
} else {
UnityEngine.Debug.Log (log);
}
}
public void NotifyDone(){
if(onDone != null){
onDone();
}
}
public void Error(){
if(onError != null){
onError();
}
}
}
private static string shellApp{
get{
#if UNITY_EDITOR_WIN
string app = "cmd.exe";
#elif UNITY_EDITOR_OSX
string app = "bash";
#endif
return app;
}
}
private static List<System.Action> _queue = new List<System.Action>();
static ShellHelper(){
_queue = new List<System.Action>();
EditorApplication.update += OnUpdate;
}
private static void OnUpdate(){
for(int i = 0;i<_queue.Count;i++){
try{
var action = _queue[i];
if(action != null){
action();
}
}catch(System.Exception e){
UnityEngine.Debug.LogException(e);
}
}
_queue.Clear();
}
public static void ProcessCommandSync(string cmd, string workDirectory, Dictionary<string, string> envVars = null) {
ProcessStartInfo start = new ProcessStartInfo(shellApp);
#if UNITY_EDITOR_OSX
start.Arguments = "-c";
#elif UNITY_EDITOR_WIN
start.Arguments = "/c";
#endif
if (envVars != null) {
foreach (var kv in envVars) {
if (start.EnvironmentVariables.ContainsKey(kv.Key)) {
start.EnvironmentVariables[kv.Key] = kv.Value;
} else {
start.EnvironmentVariables.Add(kv.Key, kv.Value);
}
}
}
start.Arguments += (" \"" + cmd + " \"");
start.CreateNoWindow = true;
start.ErrorDialog = true;
start.UseShellExecute = false;
start.WorkingDirectory = workDirectory;
start.RedirectStandardOutput = false;
start.RedirectStandardError = false;
start.RedirectStandardInput = false;
Process p = Process.Start(start);
p.WaitForExit();
UnityEngine.Debug.LogFormat("Finish running {0}", cmd);
}
public static ShellRequest ProcessCommand(string cmd, string workDirectory, Dictionary<string, string> envVars = null, bool isSync = false){
ShellRequest req = new ShellRequest();
System.Threading.ThreadPool.QueueUserWorkItem(delegate(object state) {
Process p = null;
try{
ProcessStartInfo start = new ProcessStartInfo(shellApp);
#if UNITY_EDITOR_OSX
start.Arguments = "-c";
#elif UNITY_EDITOR_WIN
start.Arguments = "/c";
#endif
if (envVars != null) {
foreach (var kv in envVars) {
if (start.EnvironmentVariables.ContainsKey(kv.Key)) {
start.EnvironmentVariables[kv.Key] = kv.Value;
} else {
start.EnvironmentVariables.Add(kv.Key, kv.Value);
}
}
}
start.Arguments += (" \"" + cmd + " \"");
start.CreateNoWindow = true;
start.ErrorDialog = true;
start.UseShellExecute = false;
start.WorkingDirectory = workDirectory;
if(start.UseShellExecute){
start.RedirectStandardOutput = false;
start.RedirectStandardError = false;
start.RedirectStandardInput = false;
} else{
start.RedirectStandardOutput = true;
start.RedirectStandardError = true;
start.RedirectStandardInput = true;
start.StandardOutputEncoding = System.Text.UTF8Encoding.UTF8;
start.StandardErrorEncoding = System.Text.UTF8Encoding.UTF8;
}
p = Process.Start(start);
p.ErrorDataReceived += delegate(object sender, DataReceivedEventArgs e) {
UnityEngine.Debug.LogError(e.Data);
};
p.OutputDataReceived += delegate(object sender, DataReceivedEventArgs e) {
UnityEngine.Debug.LogError(e.Data);
};
p.Exited += delegate(object sender, System.EventArgs e) {
UnityEngine.Debug.LogError(e.ToString());
};
bool hasError = false;
do{
string line = p.StandardOutput.ReadLine();
if(line == null){
break;
}
line = line.Replace("\\","/");
_queue.Add(delegate() {
req.Log(0,line);
});
}while(true);
while(true){
string error = p.StandardError.ReadLine();
if(string.IsNullOrEmpty(error)){
break;
}
hasError = true;
_queue.Add(delegate() {
req.Log(1,error);
});
}
p.Close();
if(hasError){
_queue.Add(delegate() {
req.Error();
});
}
else {
_queue.Add(delegate() {
req.NotifyDone();
});
}
}catch(System.Exception e){
UnityEngine.Debug.LogException(e);
if(p != null){
p.Close();
}
}
});
return req;
}
private Dictionary<string, string> _enviroumentVars = new Dictionary<string, string>();
public void AddEnvironmentVars(string key, string value){
if (key == null || value == null)
return;
if (string.IsNullOrEmpty(key.Trim()))
return;
if (_enviroumentVars.ContainsKey(key))
_enviroumentVars[key] = value;
_enviroumentVars.Add(key, value);
}
public ShellRequest ProcessCMD(string cmd,string workDir){
return ShellHelper.ProcessCommand(cmd,workDir,_enviroumentVars);
}
}
Example : Use MSBuild Compiled Dll
[MenuItem("ILRuntime/ Copy Release Dll")]
public static void CopyReleaseDll()
{
string msbuildPath = "C:/Program Files (x86)/Microsoft Visual Studio/2019/Community/MSBuild/Current/Bin";
string exe = "MSBuild.exe";
string hotfixProject = Path.Combine(Environment.CurrentDirectory, "PlatformHotfix.csproj");
ShellHelper.ProcessCommandSync($"\"{
exe}\" \"{
hotfixProject}\" /t:Clean,Build /p:configuration=\"release\"", msbuildPath);
var folder = Path.GetDirectoryName(IL_HotFixFile_Dll1);
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
if (File.Exists(Release_HotfixDll1))
{
File.Copy(Release_HotfixDll1, IL_HotFixFile_Dll1, true);
File.Copy(Release_HotfixPdb1, IL_HotFixFile_PDB1, true);
Debug.Log($" Successfully copied Hotfix.dll, Hotfix.pdb To Catalog " + folder);
AssetDatabase.Refresh();
}
}
边栏推荐
- Go encoding package
- 启牛推荐开通的证券账户安全吗?靠谱吗
- 移动端——swipe特效之图片时间轴
- Collection of articles and literatures related to R language (continuously updated)
- Dynamics 365 选项集操作
- 超标量处理器设计 姚永斌 第2章 Cache --2.4 小节摘录
- Glory earbud 3 Pro with three global first strong breakdowns flagship earphone Market
- Unity中使用调用Shell的命令行
- How to view computer graphics card information in win11
- Addition without addition, subtraction, multiplication, Division
猜你喜欢

Zhanrui IOT chip 8910dm is certified by Deutsche Telekom

BUUCTF(5)

Basic operation and question type summary of binary tree

【解决】修改子物体Transform信息导致变换不对称、异常问题的解决方案

Tkinter学习笔记(三)

Tkinter学习笔记(二)

Simple example of logistic regression for machine learning

R language book learning 03 "in simple terms R language data analysis" - Chapter 10 association rules Chapter 11 random forest

How to view computer graphics card information in win11

Implementation stack and queue
随机推荐
Tkinter study notes (III)
玩家必读|Starfish NFT进阶攻略
如果重来一次高考,我要好好学数学!
点云读写(二):读写txt点云(空格分隔 | 逗号分隔)
926. 将字符串翻转到单调递增
判断链表是否为回文结构
If I take the college entrance examination again, I will study mathematics well!
Superscalar processor design yaoyongbin Chapter 2 cache -- Excerpt from subsection 2.3
什么是死锁?(把死锁给大家讲明白,知道是什么,为什么用,怎么用)
C language implements eight sorts of sort merge sort
R language book learning 03 "in simple terms R language data analysis" - Chapter 12 support vector machine Chapter 13 neural network
Precision twist jitter
STM32 Development Notes 112:ads1258 driver design - read register
Why is the printer unable to print the test page
FastAPI 5 - 常用请求及 postman、curl 使用(parameters,x-www-form-urlencoded, raw)
One question of the day - delete duplicates of the ordered array
Unity3D getLaunchIntentForPackage 获取包返回null问题
大学三年应该这样过
R language book learning 03 "in simple terms R language data analysis" - Chapter 10 association rules Chapter 11 random forest
【解决】修改子物体Transform信息导致变换不对称、异常问题的解决方案