Run Python in Unity - integration - solve the problems you may encounter

This article aims to introduce how to call and execute Python programs in Unity. Unlike the past, which can only run Python programs in advance, the integrated method can freely control the opening of Python programs according to the changes of certain parameters in Unity. In addition, we also provide solutions to problems that may be encountered during the process.

Hope to help you. ✿✿ヽ(°▽°)ノ✿


1. Introducing the Python module into Unity

1. Open the file

Find the Package folder in the same directory as the Unity program Assets ; open the packages-lock.json file in Notepad .
insert image description here insert image description here


2. Modify the file

Add a line "com.unity.scripting.python": "5.0.0-pre.5",Note that there is a comma. After saving, return to Unity and wait for the corresponding package to be installed automatically.
insert image description here


3. Python Control Panel in Unity

Open the Python control panel under Window /General/Python Console . If you can reach this step, it means that the interface installation is successful.
insert image description here


4. Test it

The upper part is the result output platform, and the lower part is the python script writing area. Click " Execute " to execute the script.
Of course, scripts can also be obtained externally, just click " Load " and select the Python script you want to add.
insert image description here


2. Call Python from the script in Unity

1. Store the Python folder

In the Unity program, create a new folder for storing the Python program. The path of python in this article is as follows.
insert image description here
The code of the script is as follows, its function is to find the Para object in Unity and modify its name.
If an error is reported at runtime: ‘gbk‘ codec can‘t decode byte 0x80, go to Section 3.1.

import UnityEngine as ue  #这个会划红线报错,不用管
object =ue.Object.FindObjectsOfType(ue.GameObject) #获取Unity中所有的GameObject类型
for go in object:
    if go.name =="Para": #找到一个名字是“Para”物体 就把它的名字改成“123”
        go.name="123"
    else:
        ue.Debug.Log(go.name) # 在Unity的控制台中输出物体的名字

2. Unity call

① Import the header file: using UnityEditor.Scripting.Python;
② Obtain the path of the Python file: string python_path = Application.dataPath + "/Python/Python_Unity.py";
③ Set the opening condition: Let's take pressing the A key as an example.
④ Run the Python file: callPythonRunner.RunFile

The overall code is as follows. Go back to Unity and run it. When the A key is pressed, the name of the object named "Para" in the scene will be changed to "123".

void Update()
    {
    
    
        if (Input.GetKeyDown(KeyCode.A))
        {
    
    
            string python_path = Application.dataPath + "/Python/Text_Sentiment.py";
            PythonRunner.RunFile(python_path);
        }
    }

So far, how to run the Python program in the script has been introduced.
However, there are still some problems in practical applications, which we will expand in the next chapter.


3. Problems in practice

1. The gbk problem occurred in running the Python file

An error may be reported at runtime:UnicodeDecodeError: ‘gbk‘ codec can‘t decode byte 0x80 in position 0: illegal multibyte sequence

I really appreciate this mistake! (bald...)

Solution : Delete all comments in the Python file, that is, there is no "pound key".


2. com.unity.scripting.python version

In Section 1.2, the unity.scripting.python we downloaded is version 5.0.0, and the Python version installed in Unity is 3.9, and this cannot be changed. You can view detailed information in Project Setting/Python Scripting . If you want to change other versions, you can refer to this link Using Python in Unity .

insert image description here


3. The environment where the program was running before is inconsistent with the Python environment in Unity

Generally speaking, the Python program ( denoted as A.py ) that we want to call in Unity , we have successfully run it in a Python environment in Pycharm in advance ( assuming that A.py runs successfully in Python=3.6 ). In addition, it may also depend on other packages, which need to correspond to the python version in order to run normally.

So, A.py 直接在Unity的python=3.9 环境下运行可能会报错. In addition, the packages required in the program are not available in the environment under Unity. Because, now the program depends on one sit-package 即 Assets/sit-package.


To solve this problem, I think there are three ways:

① In Unity's Python=3.9 environment, re-pip install the required packages;

Click Spawn shell in enviorment under the Python Scripting panel , and the installation of the package is consistent with the configuration of Python.

Note :
This method may work, but it may still be wrong, because after all, the package is installed in Unity. Errors may occur due to the Unity platform itself. When I was trying, I kept reporting an error when importing a certain package (specifically which one I forgot> <). So, you can try the latter two methods.

insert image description here
insert image description here


② Add site-package;

Assuming that A.py is running in Python=3.6 , add the sit-package under the environment of python=3.6 that normally runs A.py.
Copy the path to the Python Scripting panel and restart Unity to take effect.

Note:
This method is basically no problem and is recommended.
But when you are running multiple Python programs, the environment of each program may be different, which requires adding multiple site-packages. When the Unity script executes PythonRunner.RunFile , the site-package under the Element 1 path may be executed first, and an error will still be reported if it is not the corresponding environment information. Here I have not studied whether PythonRunner can specify the function of site-package. Go straight to the third method! Once and for all!

insert image description here
insert image description here


③ Re-create a python=3.9 environment;
finally, when I execute Python in Unity, I still use the last method. under conda 新建了一个虚拟环境,且在python=3.9版本下配置环境. Then, add the site-package corresponding to this environment to the path mentioned in ②.

I used this method to achieve the function I want to achieve.
Therefore, everyone should choose a solution according to the actual situation of A.py.
Finally, if you have any questions, please leave a message and exchange~


Written at the end
This year has passed so fast, I also hope that I can succeed, come on!

Guess you like

Origin blog.csdn.net/LLLQQQismmmmme/article/details/128185457