unity-tolua注册delegate

unity-tolua注册delegate


步骤

  1. 定义一个 delegate

    1
    2
    3
    4
    public class GameMgr : MonoBehaviour {
    [NoToLua]
    public delegate string ShopSize(string name, int age);
    }
  2. 导出 delegate

    1. CustomSettings.cs 添加 delegate 导出配置

      1
      2
      3
      4
      //附加导出委托类型(在导出委托时, customTypeList 中牵扯的委托类型都会导出, 无需写在这里)
      public static DelegateType[] customDelegateList = {
      _DT(typeof(GameMgr.ShopSize)),
      };
    2. 导出 delegate

      • 导出的代码会在 DelegateFactory.cs 文件中, 这个 tolua 会自动调用, 不需要再进行注册
  3. 使用

    1. 添加一个 delegate 变量

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      public class GameMgr : MonoBehaviour {
      public ShopSize luaSzFn; // delegate 变量

      // 测试
      void Update() {
      if (luaSzFn != null) {
      string msg = luaSzFn("hello", 123);
      Debug.LogFormat("--- GameMgr.Update, msg: {0}", msg);
      }
      }
      }
    2. 导出 wrap 文件

    3. lua 中使用

      1
      2
      3
      gGameMgr.luaSzFn = function(name, age)
      return string.formatExt("--- name: {0}, age: {1}", name, age)
      end
      • 然后就可以看到 update 日志了