XLua與C#的通訊呼叫(獲取Unity元件)
阿新 • • 發佈:2020-09-13
using UnityEngine; using System.Collections; using XLua; using System; using System.Collections.Generic; public class LuaPacke:MonoBehaviour { private TextAsset LuaScript; private LuaTable runFunctionTable;//定義一個Lua表 public Action _luaAwake, _luaStart, _luaUpdate;//註冊Awake, Start, Update方法private void Awake() { OverridAwake(); } private void Start() { OverridStart(); } private void Update() { OverridUpdate(); } /// <summary> /// 初始化Lua指令碼 /// </summary> /// <param name="path">lua指令碼的路徑</param> publicvoid InitLuaFunction(string path) { LuaScript = Resources.Load<TextAsset>(path);//通過Resources.load獲取Lua指令碼 if(LuaScript==null) { Debug.Log(path + "is null"); return; } runFunctionTable = LuaInitScript.luaEnv.NewTable();//初始化Lua表LuaTable meatTable = LuaInitScript.luaEnv.NewTable(); meatTable.Set("__index", LuaInitScript.luaEnv.Global);//設定__index元方法,指向LuaInitScript.luaEnv.Global runFunctionTable.SetMetaTable(meatTable);//設定元表 meatTable.Dispose();//釋放 meatTable runFunctionTable.Set("self", this); LuaInitScript.luaEnv.DoString(LuaScript.text, LuaScript.name, runFunctionTable);//通過runFunctionTable執行Lua指令碼 //賦值Awake, Start, Update方法 _luaAwake = runFunctionTable.Get<Action>("lua_Awake"); _luaStart = runFunctionTable.Get<Action>("lua_Start"); _luaUpdate = runFunctionTable.Get<Action>("lua_Update"); if (_luaAwake != null && _luaStart != null && _luaUpdate != null) { Debug.Log(path + "Lua 方法載入成功"); } else { Debug.Log("載入錯誤"); } } //新增控制物件 public void AddGameObject(params string []name) { for(int i=0;i<name.Length;i++) { if(runFunctionTable.Get<string>(name[i])==null) { GameObject go = GameObject.Find(name[i]); runFunctionTable.Set<string, GameObject>(name[i], go); } } } public virtual void OverridAwake() { }//重寫Awake方法 public virtual void OverridStart() { }//重寫Start方法 public virtual void OverridUpdate() { }//重寫Update方法 }
//獲取Unity元件
Lua指令碼
PlayerButton.transform:GetComponent("Button").onClick:AddListener(PalyerButtonOnClick)
C#指令碼
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class StartPanel : LuaPacke{ // Use this for initialization void Start () { InitLuaFunction("StartPanel.lua"); AddGameObject("PlayerButton", "VoliceButton", "SettingButton", "GameButton", "EmailButton"); _luaAwake(); } // Update is called once per frame void Update () { } }