2023-05-18 build Unity Python Scripting

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
    }

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;
            }
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容