Call Python from Unity: Step-by-Step Guide

Calling Python methods in Unity usually requires using Python’s standard libraries sys and subprocess. The specific steps are as follows:

  1. First, ensure that the Python environment has been installed and configured properly.
  2. Create a C# script in Unity, instantiate a process object using the System.Diagnostics.Process class, and specify the Python interpreter and Python script file to be executed.
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);
    }
}
  1. Place the Python script file (your_python_script.py) in the Assets folder of the Unity project, ensuring the correct path for the Python script.
  2. Attach the PythonCaller script to a game object in Unity, then run the game to call the Python script and get the output.
bannerAds