转载:https://blog.csdn.net/u011048906/article/details/132920272?fromshare=blogdetail&sharetype=blogdetail&sharerId=132920272&sharerefer=PC&sharesource=qq_43530773&sharefrom=from_link
1、
首先搭建lua的开发环境需要从github上下载lua的库,下载链接为 https://github.com/Tencent/xLua
下载之后的压缩包xLua-master解压,解压后的assets文件夹才是我们需要的最终文件
2、
将assets里面的文件内容拷贝到unity项目的assets目录中去,当我们看到如下菜单界面的时候就说明我们的环境已经配置ok了
(注:新版的这个assets文件夹里有个参考用的Examples文件夹(Assets\XLua\Examples),记得删掉,不然会报错)
3、
为各类文件路径配置,新建下列文件夹:
LuaScripts——管理lua脚本
Scripts——管理C#脚本
StreamingAssets——保存本地的资源文件这个文件夹里面的资源会被打到包中去
editor——用于编辑扩展代码 普通游戏代码不要放入这个文件夹里面。
4、unity Lua代码编写
在我们已经创建好的LuaScripts文件夹下面创建main.lua的lua文件代码如下
main.lua
main = {} -- main是一个全局模块;
local function start()
print("game started")
end
main.start = start
return main
5、unity C#代码编写
c#的处理主要有两块 一块是初始化lua的环境 另一块是调用lua文件的代码
LuaLoader.cs
public class LuaLoader : MonoBehaviour
{
private LuaEnv luaEnv = null;
void Start()
{
luaEnv = new LuaEnv();
luaEnv.AddLoader(MyLuaLoader);
LoadScript("main");
SafeDoString("main.start()");//执行脚本
//清除Lua中没有手动释放的对象 进行垃圾回收
//帧更新中定时执行 或者 切场景时执行
luaEnv.Tick();
//销毁Lua解析器
luaEnv.Dispose();
}
public static byte[] MyLuaLoader(ref string filePath)
{
string scriptPath = string.Empty;
filePath = filePath.Replace(".", "/") + ".lua";
scriptPath += Application.dataPath + "/LuaScripts/" + filePath;
return GameUtility.SafeReadAllBytes(scriptPath);//通过文件IO读取lua内容
}
public void LoadScript(string scriptName)
{
SafeDoString(string.Format("require('{0}')", scriptName));
}
public void SafeDoString(string scriptContent)
{ // 执行脚本, scriptContent脚本代码的文本内容;
if (this.luaEnv != null)
{
try
{
luaEnv.DoString(scriptContent); // 执行我们的脚本代码;
}
catch (System.Exception ex)
{
string msg = string.Format("xLua exception : {0}\n {1}", ex.Message, ex.StackTrace);
Debug.LogError(msg, null);
}
}
}
}
GameUtility.cs
public static byte[] SafeReadAllBytes(string inFile)
{
try
{
if (string.IsNullOrEmpty(inFile))
{
return null;
}
if (!File.Exists(inFile))
{
return null;
}
File.SetAttributes(inFile, FileAttributes.Normal);
return File.ReadAllBytes(inFile);
}
catch (System.Exception ex)
{
Debug.LogError(string.Format("SafeReadAllBytes failed! path = {0} with err = {1}", inFile, ex.Message));
return null;
}
}
然后把main直接挂到场景里测试,正常可得: