ulua插件下载地址 www.ulua.org,下面要说的是ulua的开发框架。
首先是 LuaLoader 类,它负责把一个 lua 的 table 加载起来,使此 lua 的 table 像一个 unity 的 component 一样挂在游戏对象上,代码如下:
using LuaInterface; using System; using UnityEngine; public class LuaLoader : MonoBehaviour { public string Name; LuaTable m_table; LuaFunction m_updateFunc; LuaFunction m_fixedUpdateFunc; /// <summary> /// 通过 Name 名,加载对应的 lua table,并将之“挂”在游戏对象上。 /// </summary> /// <returns>是否加载成功</returns> public bool Load() { if (string.IsNullOrEmpty(Name)) return false; m_table = LuaHelper.GetLuaTable(Name); if (m_table == null) return false; // Init lua m_table["transform"] = transform; m_table["gameObject"] = gameObject; // m_updateFunc = GetMethod("Update"); m_fixedUpdateFunc = GetMethod("FixedUpdate"); return true; } void Awake() { if (Load()) CallMethod("Awake"); else { if (!string.IsNullOrEmpty(Name)) // 如果 Name 为空,可能是 Add component throw new ArgumentNullException("Load lua table failed, no table in " + Name); } } void Start() { if (m_table == null) // 此处应为 Add component 的情况 { if (string.IsNullOrEmpty(Name)) throw new ArgumentException("string.IsNullOrEmpty(Name)"); if (!Load()) throw new ArgumentNullException("Load lua table failed, no table in " + Name); } CallMethod("Start"); } void Update() { if (m_updateFunc != null) m_updateFunc.Call(Time.deltaTime); } void FixedUpdate() { if (m_fixedUpdateFunc != null) m_fixedUpdateFunc.Call(); } void OnEnable() { CallMethod("OnEnable"); } void OnDisable() { CallMethod("OnDisable"); } void OnDestroy() { CallMethod("OnDestroy"); // 释放内存 m_table["transform"] = null; m_table["gameObject"] = null; m_table.Release(); m_table = null; if (m_updateFunc != null) m_updateFunc.Release(); if (m_fixedUpdateFunc != null) m_fixedUpdateFunc.Release(); LuaScriptMgr.Instance.LuaGC(); } LuaFunction GetMethod(string methodName) { return m_table != null ? m_table[methodName] as LuaFunction : null; } void CallMethod(string name) { var func = GetMethod(name); if (func != null) { func.Call(); func.Release(); // 释放内存 } } public LuaTable Table { get { return m_table; } } }