2
3

More than 3 years have passed since last update.

UnityでPythonの処理を非同期で実行した後にC#処理を行う

Posted at

やりたいこと

UnityでPython処理→C#処理の順で実行したい

この記事を書いた理由

Pythonで書いたチャットシステムをUnityで動かそうとするとC#のProcessという処理が必要になる。
しかし、Processで重い処理を同期的に行うとUnityが固まってしまう!
Processで非同期処理を行うとPythonの処理の後にC#の処理が実行できない!

実現方法

//出力されたデータを保存する変数
private StringBuilder output = new StringBuilder();

public void Python()
    {   
        //新規プロセスの立ち上げ 
        var p = new Process();
        //プロセスの設定
        p.StartInfo.FileName = pyExePath; //Pythonファイルの場所
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.CreateNoWindow = true;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.Arguments = pyCodePath; //実行するファイル名
        p.StartInfo.StandardOutputEncoding = Encoding.GetEncoding("shift_jis"); //Pythonの出力結果をshift-jisに変換

        //イベントハンドラの設定
        //pythonから出力があるたびに呼び出される
        p.OutputDataReceived += new DataReceivedEventHandler((sender, e) =>
        {
            string str = e.Data;

            if (!String.IsNullOrEmpty(str))
            {
                UnityEngine.Debug.Log(str);
                output.Append(str+"\n");
            }

        });
        p.Start();

        UnityEngine.Debug.Log("プロセス実行中に非同期で開始されます");


    }

    void Update()
    {
        if(output.Length != 0){
            UnityEngine.Debug.Log("プロセスが完了した後実行されます");
            output.Length = 0 ;
        }
    }
}

簡単な解説

Processを行う関数内に次の処理を書くとどうしてもうまくいかないため、Processで得られるPythonからの出力結果が得られたらUpdate関数で実行するという方法をとることでPython→C#というようにできました。

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3