LoginSignup
3
1

More than 3 years have passed since last update.

LuaエンジンをUnityに組み込んでみる

Posted at

目的

HTMLに対応するJavaScriptのように、前回の3Dマークアップ言語にスクリプティングシステムとしてLuaを組み込んでみたい。
そのためのとっかかりとして、UnityにLuaエンジンを組み込み、GameObjectをLuaから操作してみる。

道具立て

組み込むLuaエンジンとして、NLuaを使ってみた。
nugetなどで導入する。

Unityプロジェクトとプログラム

Unityのヒエラルキーはこんな感じ。

20191223_nlua.PNG

プログラムは、まず、以下のコードを関係する全オブジェクト(Root,Child1,Cube)にアタッチしておく。これを介してLuaからGameObjectを操作する。

NLuaTest.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace NLuaTestNS
{
    public class NLuaTest : MonoBehaviour
    {
        public NLuaTest getChild(int i)
        {
            return gameObject.transform.GetChild(i).gameObject.GetComponent<NLuaTest>();
        }

        public void setColor(int r, int g, int b, int a)
        {
            gameObject.GetComponent<Renderer>().material.color = new Color((float)r/255f, (float)g/255f, (float)b/255f, (float)a/255f);
        }

        public void setPosition(float x, float y, float z)
        {
            gameObject.transform.localPosition = new Vector3(x/10f,y/10f,z/10f);
        }

        public void setRotation(float x, float y, float z)
        {
            gameObject.transform.localRotation = Quaternion.Euler(x,y,z);
        }
    }
}

そして、以下のコードをRootにアタッチして実行。

NLuaDo.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using NLuaTestNS;
using NLua;

public class NLuaDo : MonoBehaviour
{
    private Lua state;
    private int color;

    // Start is called before the first frame update
    void Start()
    {
        state = new Lua();
        state["root"] = GetComponent<NLuaTest>();
        state.DoString("root:getChild(0):getChild(0):setColor(0,0,0,255)");
    }

    void Update()
    {
        color += 1;
        color %= 256;
        state.DoString("root:getChild(0):getChild(0):setColor("+color+","+color+","+color+",255)");
        state.DoString("root:getChild(0):getChild(0):setPosition(" + color + "," + color + "," + color + ")");
        state.DoString("root:getChild(0):getChild(0):setRotation(" + color + "," + color + "," + color + ")");
    }
}

色を変えるのと、適当なアニメーションをつけてみた。

結果

素直に動いてくれた。

20191223_nluaexec.PNG

3
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
3
1