slua本身并不提供如何把一个lua文件绑定到一个预制中,就像一个普通的继承自monobehavior的自定义脚本那样,而tolua的框架却采用了拙劣的做法:
public class LuaBehaviour : Base {
private string data = null;
private AssetBundle bundle = null;
private Dictionary<string, LuaFunction> buttons = new Dictionary<string, LuaFunction>(); protected void Awake() {
Util.CallMethod(name, "Awake", gameObject);
} protected void Start() {
Util.CallMethod(name, "Start");
} protected void OnClick() {
Util.CallMethod(name, "OnClick");
} protected void OnClickEvent(GameObject go) {
Util.CallMethod(name, "OnClick", go);
}
}
所以我琢磨了一下,在slua框架下用下面脚本来完成绑定:
using UnityEngine;
using System.Collections;
using SLua; public class LuaMonoBehavior : MonoBehaviour {
public string V_LuaFilePath; LuaTable self; [CustomLuaClass]
public delegate void UpdateDelegate(object self); UpdateDelegate ud;
UpdateDelegate enabled;
UpdateDelegate disabled;
UpdateDelegate destroyd; // Use this for initialization
void Start () {
LuaState.main.doFile(V_LuaFilePath);
self = (LuaTable)LuaState.main.run("main");
var update = (LuaFunction)self["update"];
var destroy = (LuaFunction)self["destroy"];
var enablef = (LuaFunction)self["enable"];
var disablef = (LuaFunction)self["disable"];
if (update != null) ud = update.cast<UpdateDelegate>();
if (destroy != null) destroyd = destroy.cast<UpdateDelegate>();
if (enablef != null) enabled = enablef.cast<UpdateDelegate>();
if (disablef != null) disabled = disablef.cast<UpdateDelegate>();
} void OnEnable()
{
if (enabled != null) enabled(self);
} void OnDiable()
{
if (disabled != null) disabled(self);
} // Update is called once per frame
void Update () {
if (ud != null) ud(self);
} void OnDestroy()
{
if (destroyd != null) destroyd(self);
}
}
对一个新预制,我们只需要挂上LuaMonoBehavior脚本并加上对应Lua文件路径即可,然后就在你的lua文件里控制逻辑了,这对热更新非常友好。