Unity是組件式開發,腳本繼承自monobehaviour,然後掛在在gameobject上來驅動遊戲,沿着這條思路,我們設計一個自己的behaviour來驅動lua腳本。
using UnityEngine;
using LuaInterface;
public class LuaMono : MonoBehaviour
{
public string ModualName;
public LuaTable Table { get; private set; }
private LuaFunction m_awakeFunc;
private LuaFunction m_startFunc;
private LuaFunction m_enableFunc;
private LuaFunction m_disableFunc;
private LuaFunction m_destroyFunc;
private LuaFunction m_clickFunc;
private void Awake()
{
if (Table == null)
{
object[] objs = LuaManager.Instance.DoFile(ModualName);
Table = objs[0] as LuaTable;
if (Table == null)
{
Debug.LogError("cant find lua table");
}
}
GetFunction();
if (m_awakeFunc != null)
{
m_awakeFunc.Call(gameObject);
}
}
protected virtual void GetFunction()
{
m_awakeFunc = Table.GetLuaFunction("Awake");
m_startFunc = Table.GetLuaFunction("Start");
m_enableFunc = Table.GetLuaFunction("OnEnable");
m_disableFunc = Table.GetLuaFunction("OnDisable");
m_destroyFunc = Table.GetLuaFunction("OnDestroy");
m_clickFunc = Table.GetLuaFunction("OnClick");
}
private void Start()
{
if (m_startFunc != null)
{
m_startFunc.Call();
}
}
private void OnEnable()
{
if (m_enableFunc != null)
{
m_enableFunc.Call();
}
}
private void OnDisable()
{
if (m_disableFunc != null)
{
m_disableFunc.Call();
}
}
private void OnClick()
{
if (m_clickFunc != null)
{
m_clickFunc.Call();
}
}
private void OnDestroy()
{
if (m_destroyFunc != null)
{
m_destroyFunc.Call();
}
}
private void Reset()
{
ModualName = gameObject.name;
}
}
我們在一開始的時候獲取luaTable,所有lua腳本的最後我們要把luaTable return出來。