Unity3D 基于XLua框架实现Lua组件化开发方式(一)----基于C#调用Lua

2 篇文章 0 订阅
1 篇文章 0 订阅

众所周知Unity的开发语言是C#,并不支持Lua语言,为了解决这一问题出现了诸如Xlua、ULua、ToLua等框架来让unity支持lua,由于为了应对众多游戏经常需要解决的热更新问题,出了两种主流开发模式:

  1. 开发语言仍然用C#,用lua做热更新。
  2. 开发语言和热更新完全采用lua语言。

其中XLua是腾讯开发的目前行业做游戏热更新最常用的框架,本篇文章就是为了简单介绍两种如何在unity中使用lua语言做到像c#一样的组件化开发模式。

 

一、git下载xlua框架:

前往github下载xlua框架:https://github.com/Tencent/xLua

 

得到后把Xlua空间Asset目录下的全部文件放到新建的Unity项目的Asset中就可以了。

二、搭建C#调用Lua环境:

第一种方式是通过C#间接调用Lua实现组件化模式:

首先在场景中创建一个空节点挂上新建的GameLaunch.cs脚本,搭建好C#调用Lua的运行环境:

using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using XLua;

public class GameLaunch : MonoBehaviour
{
    private LuaEnv luaEnv = null;

    //将Lua读取为字节流
    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;
        }
    }

    //装载器
    public static byte[] CustomLoader(ref string filePath)
    {
        string scriptPath = string.Empty;
        scriptPath = Path.Combine(Application.dataPath, "LuaScripts"); //路径变成Asset/LuaScripts
        scriptPath = Path.Combine(scriptPath, filePath); 

         Debug.Log("Custom Load lua script : " + scriptPath);
        return SafeReadAllBytes(scriptPath);
    }

    public void Init()
    {
        this.luaEnv = new LuaEnv(); 
        if (this.luaEnv != null)
        {
            this.luaEnv.AddLoader(CustomLoader);
        }
    }

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

    public void LoadScript(string scriptName)
    { 
        SafeDoString(string.Format("require('{0}')", scriptName)); //
    }

    public void EnterLuaGame()
    { // 进入游戏 
        if (this.luaEnv != null)
        {
            this.LoadScript("MainLua.lua");  
        }
    }

    private void Awake()
    {
        this.Init();
    }

    void Start()
    {
        this.EnterLuaGame();
    }

    void Update()
    {
        
    }
}

这里我们规定路径是在Asset/LuaScripts下创建Lua脚本,比如上面我们暂时固定让他调用MainLua.lua,然后加入一个打印方法:

运行:

三、基于C#调用Lua

环境没有问题之后,就是利用C#来间接实现Lua组件化模式,在MainLua.lua中加入OnAwake,OnStart,OnUpdate等组件化方法:

然后在GameLanch.cs的组件化方法中调用:

这样就将组件中常用的方法都调用到了,接下来比如我们在OnAwake中创建一个Cube对象:

print("Main Lua!")

MainLua = {}
UnityEngine = CS.UnityEngine
GameObject = UnityEngine.GameObject

function  OnAwake()
	print("MainComponent:OnAwake")

    gameObejct = GameObject.CreatePrimitive(UnityEngine.PrimitiveType.Cube)
    gameObejct.transform.localPosition = UnityEngine.Vector3(1, 1, 1)
end

local function  OnStart()
	print("MainComponent:OnStart")
end

local function  OnUpdate()
	print("MainComponent:OnUpdate")
end

MainLua.OnAwake = OnAwake
MainLua.OnStart = OnStart
MainLua.OnUpdate = OnUpdate

return MainLua

运行:

这样也创建出来了,如果要使用Unity引擎中的API,就通过Xlua封装的CS.UnityEngine就可以了,虽然这样做到了lua组件化开发,但毕竟还是借助了C#脚本,后面奎斯会介绍另一种纯Lua的方式来实现组件化,除了Xlua的启动入口脚本GameLaunch外,其他任何节点对象上不用挂载任何C#脚本

  • 3
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值