Python Scripting介绍和使用
Python Scripting 是Unity官方提供的Unity接Python的方案,但是由于懒狗的原因,目前只支持Editor内使用。
Python Scripting主要做了以下几件事情
1.导入pythonnet
2.自动配置好pythonnet所需的python环境(win、macos、linux等都需要不同的配置)
3.与unity editor的链接,并在editor内创建如图所示的脚本编辑窗口
脚本编辑
build中使用
要在build中使用pythonnet,主要要做的事情是
- 整一个pythonnet所需的环境(我是通过安装python scripting这个包来整的,安装这个包时unity会创建一个Library\PythonInstall,这里已经是集成好的环境了,我用的就是它,用完之后再把它卸载掉。可能用venv直接在StreamingAssets下创建一个虚拟环境,然后将剩下所需的手动移进去也是可行的)
-
把pythonnet所需的python环境(不同目标平台所需的不同)转移到StreamingAsset里去
示意图 - 然后修改环境配置使pythonnet能够找到其中的所需的PythonPath和PythonDLL
- 接下来就是提取python scripting中你所需的部分,由于看起来简书不允许卑微的发200行的代码,我只能把其中PythonSetting的部分先放上来了
public sealed class PythonSettings : ScriptableObject
{
public static string kDefaultPythonDirectory = Path.Combine(Application.streamingAssetsPath, "PythonInstall");// "Library/PythonInstall";
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
public static string kDefaultPython = kDefaultPythonDirectory + "/python.exe";
#elif UNITY_EDITOR_OSX || UNITY_EDITOR_LINUX
public static string kDefaultPython = kDefaultPythonDirectory + "/bin/python" + PythonRunner.PythonMajorVersion;
#endif
}
- 最终的调用示意,这里开始就可以参考pythonnet的文档了
public class PythonInit : MonoBehaviour
{
private void Start()
{
PythonRunner.EnsureInitialized();
using (Py.GIL())
{
dynamic sys = Py.Import("sys");
}
}
private void Update()
{
using (Py.GIL())
{
try
{
dynamic t1 = Py.Import("game");
dynamic a = (t1.a);
}
catch (PythonException e)
{
Debug.Log(e);
throw;
}
}
}
}