Unity C#执行bat脚本

 我们先封装一下接口,如下,把EdtUtil.cs放置在Assets/Editor目录中

// EdtUtil.cs

using System;
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Text;

class EdtUtil
{
    public static System.Diagnostics.Process CreateShellExProcess(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);
    }
    
    public static void RunBat(string batfile, string args, string workingDir = "")
    {
        var p = CreateShellExProcess(batfile, args, workingDir);
        p.Close();
    }
    
    public static string FormatPath(string path)
    {
        path = path.Replace("/", "\\");
        if (Application.platform == RuntimePlatform.OSXEditor)
            path = path.Replace("\\", "/");
    }
}

 

现在,我们在工程Assets外层有一个batFiles目录,里面有一个gen_client_cfg.bat脚本

我们想通过Unity菜单执行这个脚本,例

using UnityEngine;
using UnityEditor;

class Test
{
    private static void RunMyBat(string batFile,string workingDir)
    {
        var path = EdtUtil.FormatPath(workingDir);
        if (!System.IO.File.Exists(path))
        {
            GameLogger.LogError("bat文件不存在:" + path);
        }
        else
        {
            EdtUtil.RunBat(batFile, "", path);
        }
    }
    
    [MenuItem("Tools/执行gen_client_cfg.bat")]
    private static void Run()
    {
        // 执行bat脚本
        RunBat("gen_client_cfg.bat", Application.dataPath + "/../batFiles/");
    }
}

点击菜单 【Tools】-【执行gen_client_cfg.bat】即可在Unity中直接执行bat脚本了

 

 

 

 

 

 

你可能感兴趣的:(C#,unity3D)