1. 程式人生 > >Lua和Unity互動

Lua和Unity互動

1、設定 package.path

用於require查詢Lua載入器的路徑

在啟動時,Lua使用環境變數LUA_PATH或者如果環境變數未定義就使用luaconf.h中定義的預設值來初始化該值.環境變數中的任何"::"都被替換為預設路徑.

路徑是一系列由分號隔開的模板(templates).對於每個模板,require將每個模板中的問號替換為filename,filename是modname中每個點都被替換成"目錄分隔符"(比如Unix中的"/")(這句感覺翻譯不準確,原文:For each template,require will change each interrogation mark in the template by filename,which is modname with each dot replaced by a "directory separator"(such as "/" in Unix));之後他將載入產生的檔名.因此,舉個例子,如果Lua預設路徑是”

LUA: .\?.lua;D:\Program Files\Unity\Editor\lua\?.lua;D:\Program Files\Unity\Editor\lua\?\init.lua;“,為模組foo查詢一個Lua載入器將會嘗試以如下順序載入檔案./foo.lua、D:/Program Files/Unity/Editor/lua/foo.lua、D:/Program Files/Unity/Editor/lua/foo/init.lua。

<span style="font-family:Microsoft YaHei;">luanet.load_assembly('UnityEngine') 
Application = luanet.import_type("UnityEngine.Application")
local path = Application.dataPath .."/Resources/Lua/";
local m_package_path= package.path  
package.path = string.format("%s;%s?.lua;%s?/init.lua",m_package_path, path, path)  </span>

上面Lua程式碼將Lua指令碼的預設載入路徑修改在了Unity Assets/Resources/Lua下面,當需要require該路徑下Base.Lua指令碼時只需要require "Base"即可。

2、C#中呼叫Lua中的方法

<span style="font-family:Microsoft YaHei;font-size:12px;">using UnityEngine;
using System.Collections;
using LuaInterface;

public class CallLuaFunction : MonoBehaviour {

    private string script = @"
	    a='hello world!'
            function luaFunc(message)
                print(message)
                return 42
            end
	    print(a)
        ";
     void Start () 
     {
        LuaState l = new LuaState();
        l.DoString(script);
	l["a"] = 100//給Lua中變數賦值
        LuaFunction f = l.GetFunction("luaFunc");//獲取script 中luaFunc方法
        object[] r = f.Call("I called a lua function!");//執行luaFunc方法,並接收返回值
        print(r[0]);//42
	print(l["a"] );//100
     }	
}</span>

3、Lua中呼叫C#中的方法

<span style="font-family:Microsoft YaHei;font-size:12px;">luanet.load_assembly('UnityEngine')
luanet.load_assembly('Assembly-CSharp')
LuaManager = luanet.import_type('LuaManager')//載入LuaManager這個類

local ActivityViewManager = { }

local ObjectNameTabel =
{
    MenuGrid = "MenuGrid",
}

local m_GameObject
local m_MenuGrid

function ActivityViewManager:Awake(obj)
    m_GameObject = obj
    FindAllObject()
end

function FindAllObject()
    m_MenuGrid = LuaManager.instance:FindChildObject(m_GameObject, ObjectNameTabel.MenuGrid)//使用LuaManager中的方法
end

return ActivityViewManager</span>