下载
官网
https://github.com/Tencent/xLua
将压缩包解压,找到Assets文件夹下Plugins与XLua文件夹,将这两个文件夹导入项目。
脚本
导入命名空间
using XLua;
创建/关闭虚拟机
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;
public class Test : MonoBehaviour
{
LuaEnv lua;
void Start ()
{
lua = new LuaEnv();
}
void OnDestroy()
{
lua.Dispose();
}
}
在C#中嵌入使用lua
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;
public class TestXlua : MonoBehaviour
{
//Xlua的环境核心类
LuaEnv lua = null;
void Start()
{
lua = new LuaEnv();
//执行lua程序
lua.DoString("print('ok')");
lua.DoString("CS.UnityEngine.Debug.Log('ok')");
}
void OnDestroy()
{
lua.Dispose();
}
}
创建Lua脚本并访问
在项目中创建Resources文件夹,并创建txt文本文档的文件,此文件命名为:文件名.lua
在此脚本中写入lua代码
访问上面lua脚本中的内容
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;
public class Test : MonoBehaviour
{
LuaEnv lua;
void Start ()
{
lua = new LuaEnv();
//加载Lua(此Lua脚本文件放在Resources文件夹中)
lua.DoString("require 'TestLua'");
}
void OnDestroy()
{
lua.Dispose();
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;
public class TestXlua : MonoBehaviour
{
LuaEnv lua = null;
void Start()
{
lua = new LuaEnv();
TextAsset textAsset = Resources.Load<TextAsset>("TestLua.lua");
lua.DoString(textAsset.ToString());
}
void OnDestroy()
{
lua.Dispose();
}
}
如果文件没有放在Resources文件夹中,文件类型不是txt文本文档:
在自定义文件夹中创建lua脚本
在lua脚本中写入代码
访问此lua脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;
using System.IO;
using System.Text;
public class Test : MonoBehaviour
{
LuaEnv lua;
void Start ()
{
lua = new LuaEnv();
//加载Lua
lua.AddLoader(LoadLua);
lua.DoString("require 'TestLua'");
}
byte[] LoadLua(ref string file)
{
Debug.Log(file);
string slua = File.ReadAllText(Application.dataPath + "/Lua/" + file + ".lua");
byte[] bytes = new UTF8Encoding().GetBytes(slua);
return bytes;
}
void OnDestroy()
{
lua.Dispose();
}
}