lua调用c#之Lua使用C#拓展方法

    科技2025-09-29  74

    c#代码

    using System.Collections; using System.Collections.Generic; using UnityEngine; using XLua; #region 拓展方法 /// <summary> /// 想要在lua中使用拓展方法,一定要在工具类加特性 /// 建议lua中要使用的类都加上该特性,可以提升性能 /// 如果不加该特性,除了拓展方法对应的类,其它的类虽然不会报错 /// 但是lua是通过反射机制去调用c#类 效率较低 /// </summary> [LuaCallCSharp] public static class Tools { //Testf的拓展方法 public static void Move(this Testf obj) { Debug.Log(obj.name + "is Moving"); } } public class Testf { public string name = "wo"; public void Speak(string str) { Debug.Log("wo speak " + str); } public static void Eat() { Debug.Log("eat something"); } } #endregion public class LuaCallCS : MonoBehaviour { // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } }

    lua代码

    local Testf=CS.Testf local tf=Testf() --使用静态方法 Testf.Eat() --使用成员方法 tf:Speak("nihao") --使用拓展方法,与使用普通成员方法一致,用冒号,尽管这个拓展方法是静态方法,也用冒号,将传入调用者当参数 --当调用c#中的拓展方法时,c#那个类一定要加上csharpcalllua特性 tf:Move()
    Processed: 0.014, SQL: 8