Unity项目接入xLua的一种流程

server/2025/2/11 0:07:02/

lua_0">1. 导入xlua

首先导入xlua,这个不用多说
在这里插入图片描述

2. 编写C#和Lua交互脚本

基础版本,即xlua自带的版本

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;
using System;
using System.IO;[Serializable]
public class Injection
{public string name;public GameObject value;
}/// <summary>
/// XLua的原生版本
/// </summary>
public class LuaBehaviour : MonoBehaviour
{public TextAsset luaScript;public Injection[] injections;/// <summary>/// 虚拟机唯一/// </summary>internal static LuaEnv luaEnv = new LuaEnv();/// <summary>/// 上一次的GC时间/// </summary>internal static float lastGCTime = 0; /// <summary>/// GC间隔/// </summary>internal const float GCInterval = 1f;private Action luaStart;private Action luaUpdate;private Action luaOnDestroy;private LuaTable scriptScopeTable;private void Awake(){SetPackagePath();scriptScopeTable = luaEnv.NewTable();//给scriptScopeTable设置__index元表,使其能够访问全局using (LuaTable meta = luaEnv.NewTable()){meta.Set("__index", luaEnv.Global);scriptScopeTable.SetMetaTable(meta);}scriptScopeTable.Set("self", this);foreach (var injection in injections){scriptScopeTable.Set(injection.name, injection.value);}//执行脚本luaEnv.DoString(luaScript.text, luaScript.name, scriptScopeTable);//获得生命周期绑定,这里直接使用scriptScopeTable,代表是使用这个脚本的全局去设置的Action luaAwake = scriptScopeTable.Get<Action>("Awake");scriptScopeTable.Get("Start", out luaStart);scriptScopeTable.Get("Update", out luaUpdate);scriptScopeTable.Get("OnDestroy", out luaOnDestroy);if (luaAwake != null){luaAwake();}}private void Start(){if (luaStart != null){luaStart();}}private void Update(){if (luaUpdate != null){luaUpdate();}if (Time.time - lastGCTime > GCInterval){luaEnv.Tick();lastGCTime = Time.time;}}private void OnDestroy(){if (luaOnDestroy != null){luaOnDestroy();}scriptScopeTable.Dispose();luaStart = null;luaUpdate = null;luaOnDestroy = null;injections = null;}/// <summary>/// 设置xlua的加载路径/// </summary>private void SetPackagePath(){//在Unity项目的“Assets”文件夹(或指定的Application.dataPath路径)及其所有子目录中,查找名为“LuaScripts”的目录,并返回一个包含这些目录路径的字符串数组foreach (string dir in Directory.GetDirectories(Application.dataPath,"LuaScripts", SearchOption.AllDirectories)){luaEnv.AddLoader(new FileLoader(dir, ".lua"));luaEnv.AddLoader(new FileLoader(dir, ".lua.txt"));}}
}

Loxodon的版本

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;
using System.IO;
using Object = UnityEngine.Object;/// <summary>
/// Loxodon的版本
/// </summary>
[LuaCallCSharp]
public class LoxodonLuaBehaviour : MonoBehaviour
{public ScriptReference script;public VariableArray variables;protected LuaTable scriptEnv;protected LuaTable metatable;protected Action<MonoBehaviour> onAwake;protected Action<MonoBehaviour> onEnable;protected Action<MonoBehaviour> onDisable;protected Action<MonoBehaviour> onUpdate;protected Action<MonoBehaviour> onDestroy;protected Action<MonoBehaviour> onStart;public LuaTable GetMetatable(){return metatable;}protected virtual void Initialize(){var luaEnv = LuaEnvironment.LuaEnv;scriptEnv = luaEnv.NewTable();LuaTable meta = luaEnv.NewTable();meta.Set("__index", luaEnv.Global);scriptEnv.SetMetaTable(meta);meta.Dispose();scriptEnv.Set("target", this);SetPackagePath(luaEnv);string scriptText = (script.Type == ScriptReferenceType.TextAsset)? script.Text.text: string.Format($"require(\"System\");local cls = require(\"{script.FileName}\");return extends(target,cls);");object[] result = luaEnv.DoString(scriptText, string.Format("{0}({1})", "LuaBehaviour", this.name), scriptEnv);if (result.Length != 1 || !(result[0] is LuaTable)){throw new Exception("");}metatable = (LuaTable)result[0];  //这里使用Lua脚本的返回值去设置,即脚本的返回值去绑定生命周期if (variables != null && variables.Variables != null){foreach (var variable in variables.Variables){var name = variable.Name.Trim();if (string.IsNullOrEmpty(name)){continue;}metatable.Set(name, variable.GetValue());}}onAwake = metatable.Get<Action<MonoBehaviour>>("Awake");onEnable = metatable.Get<Action<MonoBehaviour>>("Enable");onDisable = metatable.Get<Action<MonoBehaviour>>("Disable");onStart = metatable.Get<Action<MonoBehaviour>>("Start");onUpdate = metatable.Get<Action<MonoBehaviour>>("Update");onDestroy = metatable.Get<Action<MonoBehaviour>>("Destroy");}protected virtual void Awake(){this.Initialize();if (this.onAwake != null){this.onAwake(this);}}protected virtual void OnEnable(){if (this.onEnable != null){this.onEnable(this);}}protected virtual void OnDisable(){if (this.onDisable != null){this.onDisable(this);}}protected virtual void Start(){if (onStart != null){onStart(this);}}protected virtual void Update(){if (onUpdate != null){onUpdate(this);}}protected virtual void OnDestroy(){if (this.onDestroy != null){this.onDestroy(this);}onDestroy = null;onUpdate = null;onStart = null;onEnable = null;onDisable = null;onAwake = null;if (metatable != null){metatable.Dispose();metatable = null;}if (scriptEnv != null){scriptEnv.Dispose();scriptEnv = null;}}/// <summary>/// 修改lua的loader/// </summary>/// <param name="luaEnv"></param>private void SetPackagePath(LuaEnv luaEnv){//在Unity项目的“Assets”文件夹(或指定的Application.dataPath路径)及其所有子目录中,查找名为“LuaScripts”的目录,并返回一个包含这些目录路径的字符串数组foreach (string dir in Directory.GetDirectories(Application.dataPath,"LuaScripts", SearchOption.AllDirectories)){luaEnv.AddLoader(new FileLoader(dir, ".lua"));luaEnv.AddLoader(new FileLoader(dir, ".lua.txt"));}}
}
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;public class LuaEnvironment
{private static float interval = 2;private static WaitForSecondsRealtime wait;private static LuaEnv luaEnv;//private static IAsyncResult result;public static float Interval{get => interval;set{if (interval <= 0){return;}interval = value;wait = new WaitForSecondsRealtime(interval);}}public static LuaEnv LuaEnv{get{if (luaEnv == null){luaEnv = new LuaEnv();// if (result != null)//     result.Cancel();wait = new WaitForSecondsRealtime(interval);//result = Executors.RunOnCoroutine(DoTick());luaEnv.Tick();}return luaEnv;}}public static void Dispose(){// if (result != null)// {//     result.Cancel();//     result = null;// }if (luaEnv != null){luaEnv.Dispose();luaEnv = null;}wait = null;}private static IEnumerator DoTick(){while (true){yield return wait;try{luaEnv.Tick();}catch (Exception e){Debug.LogError(e);}}}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using Object = UnityEngine.Object;public enum ScriptReferenceType
{TextAsset,FileName
}[Serializable]
public class ScriptReference : ISerializationCallbackReceiver
{
#if UNITY_EDITOR[SerializeField]private Object cachedAsset;
#endif[SerializeField]protected TextAsset text;[SerializeField]protected string fileName;[SerializeField]protected ScriptReferenceType type = ScriptReferenceType.TextAsset;public virtual ScriptReferenceType Type => type;public virtual TextAsset Text => text;public virtual string FileName => fileName;public void OnBeforeSerialize(){Clear();}public void OnAfterDeserialize(){Clear();}protected virtual void Clear(){
#if !UNITY_EDITORswitch (type){case ScriptReferenceType.TextAsset:this.fileName = null;break;case ScriptReferenceType.FileName:this.text = null;break;}
#endif}
}

具体区别可以看两种不同的LuaBehaviour生命周期绑定

然后注意这里的lua文件读取路径设置
在这里插入图片描述
具体可以看xlua中自定义lua文件加载的一种方式
在这里插入图片描述

3.自定义属性面板

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

4. Lua脚本部分

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

因为提前设置了Lua文件的读取路径,都在LuaScripts文件夹下

运行
在这里插入图片描述

在这里插入图片描述
Lua脚本执行了对应的逻辑,将text的值变为了“你好”,同时打印了协程的输出

注意使用前让xlua生成代码
在这里插入图片描述

项目链接


http://www.ppmy.cn/server/166609.html

相关文章

【CPP】CPP经典面试题

文章目录 引言1. C 基础1.1 C 中的 const 关键字1.2 C 中的 static 关键字 2. 内存管理2.1 C 中的 new 和 delete2.2 内存泄漏 3. 面向对象编程3.1 继承和多态3.2 多重继承 4. 模板和泛型编程4.1 函数模板4.2 类模板 5. STL 和标准库5.1 容器5.2 迭代器 6. 高级特性6.1 移动语义…

网络工程师 (23)OSI模型层次结构

前言 OSI&#xff08;Open System Interconnect&#xff09;模型&#xff0c;即开放式系统互联模型&#xff0c;是一个完整的、完善的宏观模型&#xff0c;它将计算机网络体系结构划分为7层。 OSI七层模型 1. 物理层&#xff08;Physical Layer&#xff09; 功能&#xff1a;负…

运维_Mac环境单体服务Docker部署实战手册

Docker部署 本小节&#xff0c;讲解如何将前端 后端项目&#xff0c;使用 Docker 容器&#xff0c;部署到 dev 开发环境下的一台 Mac 电脑上。 1 环境准备 需要安装如下环境&#xff1a; Docker&#xff1a;容器MySQL&#xff1a;数据库Redis&#xff1a;缓存Nginx&#x…

【Prometheus】如何通过golang生成prometheus格式数据

✨✨ 欢迎大家来到景天科技苑✨✨ &#x1f388;&#x1f388; 养成好习惯&#xff0c;先赞后看哦~&#x1f388;&#x1f388; &#x1f3c6; 作者简介&#xff1a;景天科技苑 &#x1f3c6;《头衔》&#xff1a;大厂架构师&#xff0c;华为云开发者社区专家博主&#xff0c;…

Linux proc虚拟文件系统

文章目录 简介proc常用节点pid节点procfs接口参考 简介 测试环境&#xff1a;Linux dev-PC 5.18.17-amd64-desktop-hwe #20.01.00.10 SMP PREEMPT_DYNAMIC Thu Jun 15 16:17:50 CST 2023 x86_64 GNU/Linux proc虚拟文件系统是linux内核提供的一种让用户和内核内部数据结构进行交…

如何使用Spring Boot框架整合Redis:超详细案例教程

目录 # 为什么选择Spring Boot与Redis整合&#xff1f; 1. 更新 pom.xml 2. 配置application.yml 3. 创建 Redis 配置类 4. Redis 操作类 5. 创建控制器 6. 启动应用程序 7. 测试 # 为什么选择Spring Boot与Redis整合&#xff1f; 将Spring Boot与Redis整合可以充分利…

Linux系统编程:深入理解计算机软硬件体系和架构

一、硬件体系 首先我们要知道&#xff0c;我们最常见的计算机&#xff08;笔记本&#xff09;以及我们不常见的计算机&#xff08;服务器&#xff09;其实本质上都是一堆硬件的结合&#xff1a;cpu、网卡、显卡、内存、磁盘、显示器、键盘…… 但他们并不是毫无章法地放在一起…

机器学习-关于线性回归的表示方式和矩阵的基本运算规则

最近在学习机器学习的过程中&#xff0c;发现关于线性回归的表示和矩阵的运算容易费解&#xff0c;而且随着学习的深入容易搞混&#xff0c;因此特意做了一些研究&#xff0c;并且记录下来和大家分享。 一、线性模型有哪些表示方式&#xff1f; 器学习中&#xff0c;线性模型…