slua學習記錄(一)
阿新 • • 發佈:2019-01-22
1.匯入外掛後 Slua/LuaObject資料夾下的檔案全部為生成檔案,生成方式為選單中Slua -> All -> Make(每次Make之前最好先Clear一次)
2.unity - lua互動過程中的檔案有:unity C#指令碼(自寫),LuaObject資料夾下的Lua_C#檔名的指令碼(生成),對應的lua指令碼(自寫)
3.若想在lua中呼叫C#類,需在C#類中加入[CustomLuaClass]或[CustomLuaClassAttribute]屬性
如:
[CustomLuaClass]
public class Deleg : MonoBehaviour
4.lua與C#互調並簡單互動
如:只需建立一個新場景在場景中新增一個Button(UGUI),隨便給一個遊戲物件繫結LzdTest指令碼即可執行
(C#)
using UnityEngine; using System.Collections; using SLua; using System; using LuaInterface; [CustomLuaClass] public class LzdTest : MonoBehaviour { //this is a delegate public delegate void LzdTestDelegate(string path, GameObject g); static public LzdTestDelegate lzd; LuaSvr l; LuaTable self; LuaFunction update; void Start() { l = new LuaSvr(); l.init(null,()=>{ self = (LuaTable)l.start("lzdtest"); update = (LuaFunction)self["update"]; //C# call lua string str = (string)l.luaState.getFunction ("lzdFunc").call ("hello world"); Debug.Log (str); }); } void Update () { //call lua “update” function in Update if(update!=null) update.call(self); } static public void callD() { //call delegate function if (lzd != null) lzd("GameObject", new GameObject("SimpleDelegate")); Debug.Log ("callD"); } //lua call C# public void luaCallCS(string wtf) { Debug.Log (wtf); } }
(Lua)
import "UnityEngine" if not UnityEngine.GameObject then error("Click Make/All to generate lua wrap file") end local class={} function main() print("run lua main function") local cs = GameObject.Find("Main Camera") --If your class does not inheritance MonoBehaviour,you can write like this : --local h=LzdTest() --h.luaCallCS("wtf") local te = cs:GetComponent("LzdTest") te:luaCallCS("wtf") local g; --test delegate LzdTest.lzd=function(path,go) g = go print(path,go.name) end LzdTest.callD() -- test gameobject print(g.name) print(cs.name) g.transform.parent = cs.transform g:AddComponent(UnityEngine.Rigidbody) g:AddComponent(UnityEngine.BoxCollider) local c=g:AddComponent(UnityEngine.MeshRenderer) c.probeAnchor = cs.transform -- test UI local obj = GameObject.Find("Canvas/Button") local btn = obj:GetComponent("Button") local num = 0 btn.onClick:AddListener(function() num = num+1 print(" click btn ,","num = ",num) end) --if you want to use update function,you need return class return class end function lzdFunc(a) HelloWorld.nullf(1) HelloWorld.nullf() print("run this function") local name = " lzd" a = a..name return a end -- use update on lua function class:update() print(Time.deltaTime) end