Unity调用Python

1.python环境安装(自行解决)

2.Python代码编写(工具:notepad++、pycharm、文本)

import sys

#print("Hello World\nI am from Python")
listA=["red","green","blue"]
print(listA[0],listA[1],listA[2])

#两个数相加
def Add(a,b):
    a=int(a)
    b=int(b)
    return a+b

#两个数相减
def Sub(a,b):
    a=float(a)
    b=float(b)
    return a-b
print(Add(sys.argv[1],sys.argv[2]))
print(Sub(sys.argv[3],sys.argv[4]))

3.unity代码 

    /// 
	/// 
	/// 
	/// python代码文件路径
	/// 需要传递的参数数组
	private void RunPython(string path, string[] argvs)
	{
		string arguments = path;
		if (argvs != null)
		{
			foreach (string item in argvs)
			{
				arguments += (" " + item);
			}
		}
		else
		{
			return;
		}
		if (process == null)
			process = new Process();
		process.StartInfo.FileName = @"C:\Users\XXXX\AppData\Local\Microsoft\WindowsApps\python.exe";//Python代码解释器路径,写自己的路径
		process.StartInfo.UseShellExecute = false;//在python中使用sys.argv[]设置为true
		process.StartInfo.Arguments = arguments;//python脚本文件路径+参数(参数用空格隔开)
		process.StartInfo.RedirectStandardError = true;
		process.StartInfo.RedirectStandardInput = true;
		process.StartInfo.RedirectStandardOutput = true;
		process.StartInfo.CreateNoWindow = true;//是否创建窗口


		process.Start();
		process.BeginOutputReadLine();
		process.OutputDataReceived += new DataReceivedEventHandler(GetData);
		process.WaitForExit();
	}

	/// 
	/// 用于接收python返回的数据
	/// 
	/// 
	/// 
	private void GetData(object sender, DataReceivedEventArgs e)
	{
		if (string.IsNullOrEmpty(e.Data) == false)
		{
			print(e.Data);//打印从python收到的返回值
		}
	}

	private void OnDestroy()
	{
		if (process!= null)
			process.Close();
	}

你可能感兴趣的:(unity,python,unity3d,c#)