1. 程式人生 > >lua熱更框架之XLua

lua熱更框架之XLua

eric 開發 rap ons 框架 ++ 判斷 org ati

框架介紹 xLua是當下最流行的unity熱更方案之一,作者是騰訊的車雄生前輩,自2016年初推出以來,已經在騰訊的多款遊戲項目上應用,目前xLua已經開源到了GitHub。xLua最大的特色是不僅支持純lua腳本熱更,更是可以做 C# 代碼的bug hotfix,即平時開發時使用C#,項目上線後,如果突然發現有bug,可以直接用lua去修復出bug的地方,原理就是通過[Hotfix]特性標記然後在IL邏輯層判斷修改邏輯,使程序去執行更新後的lua邏輯代碼而不是走之前的C#邏輯。 框架優勢 與別的lua熱更插件不同的是,別的lua熱更方案基本都是項目中需要熱更的部分一開始就需要用lua語言去實現,xlua的HotFix出現之前,基本所有的lua熱更方案都是如此,這樣做的不足之處有:lua的性能是不如C#的,這是最主要的,此外,有些項目剛開始做時都是用C#的,如果已經用C#做完了,這時再去接入lua,把需要邏輯熱更的C#代碼重新用lua去實現,這樣就麻煩了不少,費時費力,而且兩種語言配合開發時還容易碰上傷腦筋的bug。使用xlua的HotFix,就可以平時開發用C# ,C#寫起來比lua舒服多了吧;運行的時候也是C#,性能也比lua強;可能會出現bug或者需要熱更邏輯的地方打上[HotFix]特性標簽,然後就下載lua腳本文件更新實現即可,等到下次大版本更新時,再把lua補丁換成正確的C#實現。同時,xlua的易用性更是秒殺其他lua熱更插件,在編輯器下無需生成代碼,使用簡單,不像其他lua熱更插件每次更新代碼就需要點Code Generate。 HotFix使用
xLua的純lua熱更使用方式跟其他lua熱更方案大同小異,這裏只簡單介紹一下HotFix使用。 首先,對於可能出現bug或者後期需要更新邏輯的地方,給這個類加上[HotFix]標簽,並在方法上打上[LuaCallCSharp]標簽,例如下面這個類,打上[HotFix]標簽,CreatePrize()方法上打上[LuaCallCSharp]標簽,那麽當需要更新這個方法時,只需在lua腳本中重新實現這個方法。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using XLua; [Hotfix] public class Treasour : MonoBehaviour { public GameObject gold; public GameObject diamands; public Transform cavas; [LuaCallCSharp] private void CreatePrize() { for (int i = 0; i < 5; i++) { GameObject go = Instantiate(gold, transform.position + new
Vector3(-10f + i * 30, 0, 0), transform.rotation); go.transform.SetParent(cavas); GameObject go1 = Instantiate(diamands, transform.position + new Vector3(0, 30, 0) + new Vector3(-10f + i * 30, 0, 0), transform.rotation); go1.transform.SetParent(cavas); } } }

技術分享圖片 在lua腳本中,如下:
local UnityEngine=CS.UnityEngine
xlua.hotfix(CS.Treasour,CreatePrize,function(self)
    for i=0,4,1 do
        local go=UnityEngine.GameObject.Instantiate(self.gold,self.transform.position+UnityEngine.Vector3(-10+i*40,0,0),self.transform.rotation)
        go.transform.SetParent(go.transform,self.cavas)
        local go1=UnityEngine.GameObject.Instantiate(self.diamands,self.transform.position+UnityEngine.Vector3(0,40,0)+UnityEngine.Vector3(-10+i*40,0,0),self.transform.rotation)
        go1.transform.SetParent(go1.transform,self.cavas)
    end
end)

技術分享圖片 當客戶端下載lua腳本後,就會自動執行lua中的CreatePrize方法,這樣就實現了代碼熱更。
void Start(){ 
   if(_hotfix) 
        _lua_CreatePrize;  
   else  
        _csharp_CreatePrize;
}

技術分享圖片

lua熱更框架之XLua