文章目录
- 前言
- 1 配置
- 1.1 配置宏
- 1.2 XLua配置
- 2 lua和C#相互调用
- 2.1 XLua.CSharpCallLua
- 2.2 XLua.LuaCallCSharp
- 3 加载器
前言
XLua本质上是为Unity提供了使用lua的能力,实际多用于热更新。
热更新,因为要给代码打标签才能生效,所以需要预测修改的部分,如果恰好需要修改的代码没有打上,就只能大版本更新了。
笔者使用环境:
- Unity 2021.3.8
- vs2022
- XLua 2.1.15
1 配置
1.1 配置宏
参考热补丁操作指南
unity2021修改了位置,我找了半天
Edit -> Project settings… -> Player -> Other Settings -> Scrpiting Define Symbols
1.2 XLua配置
参考Xlua配置
文章里的二级标题都是特性,比如文章中倒数第二个标题CSObjectWrapEditor.GenPath对应特性[CSObjectWrapEditor.GenPath]
,它用于修改XLua生成代码的目录,必须在Editor程序集里使用。
官方建议使用列表方式打标签,并且在Editor程序集里的静态类实现,下面举例给命名空间XluaExample下的所有类打[Hotfix]
标签。
顺便记录一下,在lua中调用有命名空间的类:CS.XluaExample.Test
namespace XluaExample
{public static class XluaConfig{[CSObjectWrapEditor.GenPath]public static string genPath = Application.dataPath + @"/Projects/XluaExample/XLua/Gen";// 需要热更新的类[Hotfix]public static List<Type> by_property{get{var t = (from type in Assembly.Load("Assembly-CSharp").GetTypes()where type.Namespace == "XluaExample"select type).ToList();return t;}}}
}
2 lua和C#相互调用
参考XLua教程
参考Tutorial(不同于Example)
没打标签就使用反射调用。
2.1 XLua.CSharpCallLua
一般用在委托和接口上,委托获取lua方法,接口获取类。
2.2 XLua.LuaCallCSharp
一般用于类(包括内部类、枚举类)、类方法。
3 加载器
参考XLua教程
参考LoadLuaScript
在xLua加自定义loader是很简单的,只涉及到一个接口:
public delegate byte[] CustomLoader(ref string filepath);public void LuaEnv.AddLoader(CustomLoader loader);
代码参考
namespace XLuaExample
{public class XLuaExample : MonoBehaviour{public static XLuaExample Instance;public LuaEnv luaEnv = new LuaEnv();private void Awake(){luaEnv.AddLoader(MyLoader);luaEnv.DoString("require'luamain'");Instance = this;Debug.Log(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase);}static byte[] MyLoader(ref string filePath){string path = Application.streamingAssetsPath + @"\Lua\" + filePath + ".lua.txt";return System.Text.Encoding.UTF8.GetBytes(File.ReadAllText(path));}}
}