0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Unityにpythonをインストールする。

Last updated at Posted at 2021-09-11

1 この記事は何?

Unityにpythonをインストールする方法を説明します。またUnity上で簡単なpythonのコードを実行してみます。

前提条件 Unity2919.4.29f1が導入されているものとします。

2 その方法は?

2-1 必要データのダウンロード

まず下記のサイトにアクセスしサイトの筆者が準備したUnity Packageをダウンロードします。

234.JPG

2-2 データの取り込み

前述のPackageをUnityにImportします。
235.JPG

AssetsフォルダにあるPythonExample.prefabを描写エリアにドラッグドロップします。

236.JPG

2-3 コーディング

まずは、pythonコードから始めます。Assetsのフォルダにgreeter.pyがあります。
237.JPG

greeter.pyを下記のとおり変更してみます。(Python2.7がインストールされています。Python3.xは使用できないことをご認識ください)

greeter.py
import random
import sys

class Greeter():
    def __init__(self, name):
        self.name = name
    def greet(self):
        return "Hiii, " + self.name
    def versionget(self):
        sysv=sys.version #pythonのverisonを取得します。
    	return "python version:" + sysv

次にC#をコーディングします。Assetsディレクトリの中に配置されているPythonExample.csを開きます。

238.JPG

下記の通り修正してください。

PythonExample.cs
using System.Collections;
using System.Collections.Generic;
using IronPython.Hosting;
using UnityEngine;

public class PythonExample : MonoBehaviour {

    // Use this for initialization
    void Start()
    {
        var engine = Python.CreateEngine();

        ICollection<string> searchPaths = engine.GetSearchPaths();

        //Path to the folder of greeter.py
        searchPaths.Add(Application.dataPath);
        //Path to the Python standard library
        searchPaths.Add(Application.dataPath + @"\Plugins\Lib\");
        engine.SetSearchPaths(searchPaths);

        dynamic py = engine.ExecuteFile(Application.dataPath + @"\greeter.py");
        dynamic greeter = py.Greeter("Mika");
        Debug.Log(greeter.greet());
        Debug.Log(greeter.versionget());
    }

    // Update is called once per frame
    void Update () {
		
	}
}

上記のコードはC#の一連の作業の中でpythonを実行します。pythonにデータを渡し、pythonから返された値をC#が受け取ります。

コーディングか終わりましたら、PythonExample.csをビルドします。

239.JPG

2-4 実行

実際に実行してみます。Gameを選択のうえ、矢印をクリックすると動作が開始されます。
240.JPG

実行結果がConsoleに表示されております。pythonコードでは、「Hii,Mika」と使用しているPython versionの表示を行っているので、C#がそれらのデータを受け取りConsoleに表示しております。

241.JPG

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?