共計 704 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Unity 中調用 Python 方法通常需要使用 Python 的標準庫 sys 和 subprocess,具體步驟如下:
-
首先確保 Python 環境已經安裝并配置好。
-
在 Unity 中創建一個 C# 腳本,使用 System.Diagnostics.Process 類實例化一個進程對象,并指定要執行的 Python 解釋器和 Python 腳本文件。
using System.Diagnostics;
public class PythonCaller : MonoBehaviour
{void Start()
{ProcessStartInfo start = new ProcessStartInfo();
start.FileName = "python";
start.Arguments = "your_python_script.py";
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
Process process = new Process();
process.StartInfo = start;
process.Start();
// 讀取 Python 腳本的輸出
string output = process.StandardOutput.ReadToEnd();
// 打印輸出
Debug.Log(output);
}
}
-
將 Python 腳本文件(your_python_script.py)放置于 Unity 項目的 Assets 文件夾下,確保 Python 腳本的路徑正確。
-
在 Unity 中將 PythonCaller 腳本附加到一個游戲對象上,運行游戲即可調用 Python 腳本并獲取輸出。
丸趣 TV 網 – 提供最優質的資源集合!
正文完