見出し画像

MacでUnityとPythonを連携させる

MacでUnityとPythonを連携させる方法を説明します。

1. Pythonスクリプトの作成

今回は、「hello, world!」と出力するだけのスクリプトを作ります。

【helloworld.py】

print('hello, world!')

2. Pythonを実行するシェルスクリプトの作成

Pythonスクリップトを実行する前にAnacondaなどで環境を整えてから実行するシェルスクリプトを記述します。

【helloworld.sh】

# >>> conda init >>>
__conda_setup="$(CONDA_REPORT_ERRORS=false '/Users/<User>/anaconda3/bin/conda' shell.bash hook 2> /dev/null)"
if [ $? -eq 0 ]; then
   \eval "$__conda_setup"
else
   if [ -f "/Users/<User>/anaconda3/etc/profile.d/conda.sh" ]; then
       . "/Users/<User>/anaconda3/etc/profile.d/conda.sh"
       CONDA_CHANGEPS1=false conda activate base
   else
       \export PATH="/Users/<User>/anaconda3/bin:$PATH"
   fi
fi
unset __conda_setup
# <<< conda init <<<

conda activate helloworld
python $(cd $(dirname $0); pwd)"/helloworld.py"

「conda init」は、Anacondaインストール時に、「.bash_profile」に追加された初期化スクリプトです。その後、「conda」で仮想環境を開き、シェルスクリプトと同じフォルダにある「helloworld.py」を実行しています。コマンドが、カレントパスに依存しないようにしています。

動作確認は「/bin/bash」で行います。

$ /bin/bash -c "/Users/<User>/HelloUnity/Assets/StreamingAssets/helloworld.sh"

bashは、以下が参考になります。

実践して学ぶBash入門

3. Unityプロジェクトの作成

(1)Unityで新規プロジェクトの作成。

(2)「/Assets/StreamAssets」に「helloworld.py」「helloworld.sh」を追加。StreamAssetsに追加することで、アプリのビルド時に、何も変換しないで実行ファイルに含めることができます。

(3)Hierarchyに「Text」を追加し、「ProcessTest.cs」を追加。
シェルスクリプトはProcessで実行できます。

【ProcessTest.cs】

using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using UnityEngine;
using UnityEngine.UI;

//Processの利用
public class ProcessTest : MonoBehaviour {
   private Text label;

   //初期化
   void Start() {
       //ラベルの取得
       this.label = this.GetComponent<Text>();

       //シェルスクリプトの実行
       string path = Application.streamingAssetsPath + "/helloworld.sh";
       Process process = new Process();
       process.StartInfo.FileName = "/bin/bash";
       process.StartInfo.Arguments = "-c \"" + path + "\"";
       process.StartInfo.UseShellExecute = false;
       process.StartInfo.RedirectStandardOutput = true;
       process.StartInfo.CreateNoWindow = true;
       process.Start();

       //結果待ち
       var output = process.StandardOutput.ReadToEnd();
       process.WaitForExit();
       process.Close();

       //ラベルに表示
       this.label.text = output;
   }
}


この記事が気に入ったらサポートをしてみませんか?