基本原理:命令行启动Unity,然后执行对应的类中的静态方法。
unity命令行参数简介:https://my.oschina.net/mbreath/blog/759480
Unity工程目录:
D: _lugsProjectsXLuaxlua
Unity安装目录:
D:1_WorkSoftwareUnity2017.2.0p4UnityEditorUnity.exe
编写CShrap代码:
1 using UnityEditor; 2 using UnityEngine; 3 4 public class EditorMenu 5 { 6 [MenuItem("Test/测试Python调用Unity方法")] 7 public static void TestPythonUnity() 8 { 9 Debug.Log("测试Python调用Unity方法"); 10 } 11 }
运行之后,将“测试Python调用Unity方法”这句话写入log文件。
编写Python脚本:
1 import os 2 import subprocess 3 import psutil 4 5 #判断进程是否正在运行 6 def Exist(process_name): 7 pl = psutil.pids() 8 for pid in pl: 9 if psutil.Process(pid).name() == process_name: 10 return pid 11 12 #杀掉运行中的Unity 13 def KillUnity(): 14 if isinstance(Exist("Unity.exe"),int): 15 os.system("taskKill /F /IM Unity.exe") 16 else: 17 print('no such process...') 18 19 def ExcuteUnityMethod(): 20 unityPath = "D:\1_WorkSoftware\Unity2017.2.0p4\Unity\Editor\Unity.exe" 21 logFilePath = "D:\0_lugsProjects\Python\Log_PythonUnity.txt" 22 projectPath = "D:\0_lugsProjects\XLua\xlua" 23 className = "EditorMenu" 24 methodName = "TestPythonUnity" 25 cmd = "%s -quit -batchmode -logFile %s -projectPath %s -executeMethod %s.%s" % (unityPath,logFilePath,projectPath,className,methodName) 26 #print(cmd) 27 subprocess.Popen(cmd) 28 29 def Main(): 30 KillUnity() 31 ExcuteUnityMethod() 32 33 Main() 34 35 input("Enter any key ...")
注意:psutil是一个模块,需要单独安装。以下网址为其介绍。
https://www.liaoxuefeng.com/wiki/1016959663602400/1183565811281984
运行python脚本结果的部分截图:
可以看到CSharp代码中的方法被正确执行了。
如果想在CSharp方法中拿到python传过去的参数该如何做呢?很简单,CSharp提供了获取命令行参数额接口,代码如下:
1 static void ParseCommandParams() 2 { 3 string[] array = System.Environment.GetCommandLineArgs(); 4 if (null != array) 5 { 6 for (int i = 0; i < array.Length; ++i) 7 { 8 DebugLog(array[i]); 9 } 10 } 11 }