xLua下载
1、HelloWrold 代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua; // 引入XLua命名空间 public class Helloworld01 : MonoBehaviour
{//声明LuaEnv对象 private LuaEnv luaenv;void Start(){//实例化LuaEnv对象luaenv = new LuaEnv();//执行lua代码 外面的双引号里面的是lua代码luaenv.DoString("print('Hello world')");}private void OnDestroy(){//释放LuaEnv对象luaenv.Dispose();}
}
输出结果:
2、环境管理规范
一个unity 项目最好只有一个 LuaEnv 实例
输出结果:
3、建立单独的Lua文件
单独的lua文件:
把lua程序放到resources文件夹里面,来加载这个程序,获取里面的字符串,把字符串当做一个参数放在C#文件中执行
- resources文件中
引用脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua; // 引入XLua命名空间 public class Helloworld02 : MonoBehaviour
{void Start(){ //文件名:helloworld.lua.txtTextAsset ta = Resources.Load<TextAsset>("helloworld.lua"); LuaEnv env = new LuaEnv();env.DoString(ta.text); // env.DoString(ta.ToString());env.Dispose();}
}
输出结果:
4、使用系统内置加载Lua的方式
5、自定义加载器Loader
1) 加载一个不存在的lua文件(利用系统内置的加载方式,自定义Loader为空)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;public class Createloader : MonoBehaviour
{void Start(){LuaEnv env = new LuaEnv();env.AddLoader(MyLoader);env.DoString("require 'XXXXXX'");env.Dispose(); }private byte[] MyLoader(ref string filePath){return null;}}
输出结果:
2) 加载helloworld lua文件(利用系统内置的加载方式,自定义Loader为空)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;public class Createloader : MonoBehaviour
{void Start(){LuaEnv env = new LuaEnv();env.AddLoader(MyLoader);env.DoString("require 'helloworld'");env.Dispose(); }private byte[] MyLoader(ref string filePath){//输出文件名 helloworldprint(filePath);//自定义loader为空return null;}}
输出结果:
输出顺序:自定义Loader ->> 系统内置的Loader
3) 加载 自定义Loader (首先执行自定义Loader程序 找到字节数组,执行自定义Loader,系统内置的Loader程序,不支执行)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;public class Createloader : MonoBehaviour
{void Start(){LuaEnv env = new LuaEnv();env.AddLoader(MyLoader);env.DoString("require 'helloworld'");env.Dispose(); }private byte[] MyLoader(ref string filePath){print(filePath);string s = "print (123)";//字符串转为字节数组//通过System.Text.Encoding.UTF8转为字节数组 //通过GetBytes() 来获取数组return System.Text.Encoding.UTF8.GetBytes(s);}}
输出结果:
6、通过 路径 加载Lua文件
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using XLua;public class Createloader : MonoBehaviour
{void Start(){LuaEnv env = new LuaEnv();env.AddLoader(MyLoader);env.DoString("require 'test007'");env.Dispose(); }private byte[] MyLoader(ref string filePath){print(filePath);//return System.Text.Encoding.UTF8.GetBytes(s);print(Application.streamingAssetsPath);//路径构建 拼接完整路径<Project>/Assets/StreamingAssets/test007.lua.textstring absPath = Application.streamingAssetsPath + "/" + filePath + ".lua.text";//File.ReadAllText(absPath):文件读取(读取指定路径的文本文件内容)//字节转换return System.Text.Encoding.UTF8.GetBytes(File.ReadAllText(absPath));}}