1.python环境安装(自行解决)
2.Python代码编写(工具:notepad++、pycharm、文本)文章来源:https://www.toymoban.com/news/detail-528223.html
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代码 文章来源地址https://www.toymoban.com/news/detail-528223.html
/// <summary>
///
/// </summary>
/// <param name="path">python代码文件路径</param>
/// <param name="argvs">需要传递的参数数组</param>
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();
}
/// <summary>
/// 用于接收python返回的数据
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!