スマゲ

スマートなゲームづくりを目指して日々精進

Unityでbashを利用する

UnityのPostProcessBuildでbashを動かしてみます。
UnityはEditor以下にPostprocessBuildPlayerファイル(拡張子なし)を作成し、シバンを記述すれば様々な実行環境でコードを走らせることができますが、今回は PostProcessBuild + Process でbashを実行します。

■環境
Unity5.3.5f1
Mac OS X

■サンプルコード
bashコマンドを文字列で受け取り、結果を返します

using UnityEngine;
using UnityEditor;
using UnityEditor.Callbacks;
using System.IO;
using System.Diagnostics;
using System.Collections;

public class PostProcessBuildProcessor {

    [PostProcessBuild]
    public static void OnPostProcessBuild(BuildTarget target, string path) {
        var output = DoBashCommand("echo hello");
        UnityEngine.Debug.Log(output);
    }

    static string DoBashCommand(string cmd){
        var p = new Process();
        p.StartInfo.FileName = "/bin/bash";
        p.StartInfo.Arguments = "-c \" " + cmd + " \"";
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardOutput = true;
        p.Start();

        var output = p.StandardOutput.ReadToEnd();
        p.WaitForExit();
        p.Close();

        return output;
    }
}

■実行結果
ビルド実行時のコンソール
f:id:sanukin39:20160621225658p:plain

■まとめ
PostprocessBuildPlayerのように特定名のファイルを作ることなくbashを実行することができた。