lua调用c#之Lua使用C#拓展方法
c#代码using System.Collections;using System.Collections.Generic;using UnityEngine;using XLua;#region 拓展方法/// <summary>/// 想要在lua中使用拓展方法,一定要在工具类加特性/// 建议lua中要使用的类都加上该特性,可以提升性能/// 如果不加该特性,除了拓展方法对应的类
·
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()
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐

所有评论(0)