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));}}