Lesson3_C#调用Lua_封装一个LuaManager
public class LuaManager
{
private static LuaManager instance;
public static LuaManager Instance
{
if(instance==null)
{
instance=new LuaManger();
}
return instance;
}
//Lua 解释器
private LuaEnv luaEnv;
//得到Lua中的_G表
public LuaTable Global
{
get
{
return luaEnv.Global;
}
}
public void Init()
{
if (luaEnv == null)
{
luaEnv = new LuaEnv();
}
luaEnv.AddLoader(MyCustomLoader);
//luaEnv.AddLoader(MyCustomABLoader); //这个路径是以后从AB包寻找脚本所设置,目前不用
}
//执行Lua语句
public void DoString(string luaStr)
{
if (luaEnv == null)
{
Debug.Log("解析器未初始化");
return;
}
luaEnv.DoString(luaStr);
}
public void DoLuaFIle(string fileName)
{
if (luaEnv == null)
{
Debug.Log("解析器未初始化");
return;
}
string str = string.Format("require('{0}')", fileName);
luaEnv.DoString(str);
}
//垃圾释放
public void Tick()
{
luaEnv.Tick();
}
//销毁解析器
public void DisPose()
{
luaEnv.Dispose();
luaEnv = null;
}
//文件加载重定向函数
private byte[] MyCustomLoader(ref string filePath)
{
//传入的参数是require执行的脚本名
string path = Application.dataPath + "/Lua/" + filePath + ".lua";
if (File.Exists(path))
{
return File.ReadAllBytes(path);
}
else
{
Debug.Log("MyCustomLoader重定向失败,文件名为 " + filePath);
}
return null;
}
//文件加载重定向至AB包
private byte[] MyCustomABLoader(ref string filePath)
{
Debug.Log("AB包加载");
/* //从AB包加载Lua文件 (不使用管理器)
//加载AB包
string path = Application.streamingAssetsPath + "/lua";
AssetBundle ab = AssetBundle.LoadFromFile(path);
//加载lua文件
TextAsset tx = ab.LoadAsset<TextAsset>(filePath+".lua");
return tx.bytes;*/
TextAsset lua= ABManager.GetInstance().LoadRes<TextAsset>("lua", filePath + ".lua");
if (lua != null)
{
return lua.bytes;
}
else
{
Debug.Log("lua文件不存在AB包,文件名" + filePath);
return null;
}
}
}

浙公网安备 33010602011771号