1. 程式人生 > >slua中,綁定lua文件到Monobehavior的一種方法

slua中,綁定lua文件到Monobehavior的一種方法

void ons 我們 gate use cli called call asset

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文件裏控制邏輯了。

slua中,綁定lua文件到Monobehavior的一種方法