unity と外部プログラムを連携したときの基本的な非同期のやり方
unity
using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine;
using System.Diagnostics;
using System.IO;
using Cysharp.Threading.Tasks;
using Debug = UnityEngine.Debug;
public class TestUniTask : MonoBehaviour
{
// Start is called before the first frame update
private string pyExePath = @"C:\meganebu\venv\Scripts\python.exe";
private ProcessStartInfo processStartInfo;
private Process process;
private StreamReader streamReader;
private string processResult;
// Basic async await with Process(ex python)
async void Start()
{
Debug.Log("Start1");
var result = await TestFunc();
Debug.Log(result);
Debug.Log("Start4");
}
private UniTask<string> TestFunc()
{
Debug.Log("Start2");
return UniTask.Run(() =>
{
processStartInfo = new ProcessStartInfo()
{
FileName = pyExePath,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true,
Arguments = @"C:\meganebu\test.py"
};
process = Process.Start(processStartInfo);
streamReader = process.StandardOutput;
processResult = streamReader.ReadLine();
process.WaitForExit();
process.Close();
Debug.Log(processResult);
Debug.Log("Start3");
return processResult;
});
}
// Update is called once per frame
void Update()
{
}
}
大事な箇所だけ、説明
\meganebu\venv\Scripts\python.exe";
ここで、あらかじめインストールしておいたpythonを指定
\meganebu\test.py"
次に、ここで、実際に実行したいpythonを指定。
実際には、ここで実行。すると、TestFunc内が実行され、pythonが実行され、pythonからの戻り、print(1)の1を受け取って、resultに入る。
ので場合よっては、python側で、処理分岐し、0、1で成否、その戻りをunityで受けてUI上に表示するとか、が良いかも。
python
import sys
import time
time.sleep(5)
print(1)
time.sleep(5)
ここは、確認用にわかりやすく入れているsleep処理。unityから呼び出した後、ちゃんと5秒待って、戻りが戻ってくる。