(帶完整demo)Unity3d熱更新xlua基於Unity2018.2.2和xlua2.1.14(小白提升乾貨)

下載xlua

https://github.com/Tencent/xLua

安裝xlua到unity工程

1 解壓後的目錄如下在這裏插入圖片描述
2 將Assets目錄下的文件複製到Unity工程的Assets目錄下
3 將Tools整個目錄複製到Unity工程與Assets的同目錄下
4 配置宏
在File/Build Settings/Player Settings,設置Scripting_Define_Symbols的值爲HOTFIX_ENABLE
如上步驟後,會發現菜單上多了一個XLua菜單
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

在這裏插入圖片描述

運行測試

1 打開XLua/Examples/08_Hotfix的 Hotfix_Test
2 在菜單XLua下,先點擊Generate Code等待編譯完成後,再點擊Hotfix Inject In Editor,再次等待編譯
3 運行,觀察到控制檯輸出爲update in c#
4 點擊Hotfix,觀察到控制檯輸出

LUA: <<<<<<<<Update in lua, tick = 9350 UnityEngine.Debug:Log(Object)
XLua.StaticLuaCallbacks:Print(IntPtr) (at
Assets/XLua/Src/StaticLuaCallbacks.cs:629)
XLua.LuaDLL.Lua:lua_pcall(IntPtr, Int32, Int32, Int32)
XLua.DelegateBridge:PCall(IntPtr, Int32, Int32, Int32) (at
Assets/XLua/Src/DelegateBridge.cs:138)
XLua.DelegateBridge:__Gen_Delegate_Imp14(Object) (at
Assets/XLua/Gen/DelegatesGensBridge.cs:340)
XLuaTest.HotfixTest:Update()
這樣我們就實現了lua調用c#
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

新建一個修復腳本HotFixTest1

這裏用來加載lua代碼到luaEnv中執行,目錄是相對路徑,放在與Assets同目錄下
在這裏插入圖片描述

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;
using System.IO;
public class HotFixTest1 : MonoBehaviour {
    private LuaEnv luaEnv;
    private void Awake()
    {
        luaEnv = new LuaEnv();
        luaEnv.AddLoader(HandleCustomLoader);
        luaEnv.DoString("require'fix'");
    }
    // Use this for initialization
    void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {

    }

    private byte[] HandleCustomLoader(ref string filepath)
    {
        string absPath = filepath + ".lua.txt";
        return System.Text.Encoding.UTF8.GetBytes(File.ReadAllText(absPath));
    }
    private void OnDisable()
    {
        luaEnv.DoString("require'fixDispose'");
    }
    private void OnDestroy()
    {
        luaEnv.Dispose();
    }


}

新建lua文件測試

1 fix.lua.txt與項目Assets同目錄下

--test
UnityEngine = CS.UnityEngine
UnityEngine.Debug.Log("test")

2 fixDispose.lua.txt暫時爲空 與項目Assets同目錄下

3 將上一步的HotFixTest1腳本掛到場景任意物體上,比如相機上

4 在菜單XLua下,先點擊Generate Code等待編譯完成後,再點擊Hotfix Inject In Editor,再次等待編譯
5 觀察到輸出了test
在這裏插入圖片描述

爲demo搭建一個加載遊戲場景

1 場景很簡單,一個Slider
在這裏插入圖片描述
2 新建腳本LoadGame

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class LoadGame : MonoBehaviour {
    public Slider slider;
    
    public string luaPath = @"http://212.64.12.155/unity/demo2/fix.lua.txt";
    // Use this for initialization
    void Start () {
        LoadGameMethod();
    }

    private void LoadGameMethod()
    {
        StartCoroutine(StartLoading(1));
        StartCoroutine(LoadResFromServerCorotine());
    }
    private IEnumerator StartLoading(int scene)
    {
        int displayProgress = 0;
        int toProgress = 0;
        AsyncOperation op = SceneManager.LoadSceneAsync(scene);
        op.allowSceneActivation = false;
        while (op.progress < 0.9f)
        {
            toProgress = (int)op.progress * 100;
            while (displayProgress < toProgress)
            {
                ++displayProgress;
                SetLoadingPercentage(displayProgress);
                yield return new WaitForEndOfFrame();
            }
        }

        toProgress = 100;
        while (displayProgress < toProgress)
        {
            ++displayProgress;
            SetLoadingPercentage(displayProgress);
            yield return new WaitForEndOfFrame();
        }
        op.allowSceneActivation = true;
    }
    private void SetLoadingPercentage(float v)
    {
        slider.value = v / 100;
    }
    IEnumerator LoadResFromServerCorotine()
    {
        UnityWebRequest request = UnityWebRequest.Get(luaPath);
        yield return request.SendWebRequest();
        string str = request.downloadHandler.text;
        string localFilePath = @"./fix.lua.txt";
        File.WriteAllText(localFilePath, str);
    }
    // Update is called once per frame
    void Update () {
		
	}
}

3將LoadGame腳本掛到MainCamera 上,然後吧Slider賦值上
在這裏插入圖片描述

爲demo搭建主場景測試

1 創建text顯示當前版本
2 新建GameManager物體
3 新建Manager腳本,內容如下

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using XLua;
using UnityEngine.Networking;
[Hotfix]
public class Manager : MonoBehaviour {
    public Text uitext;
    public GameObject parent;
    public static Dictionary<string, GameObject> prefabDict = new Dictionary<string, GameObject>();

    // Use this for initialization
    public string title = "1.0版本";
    [LuaCallCSharp]
    void Start () {
	}
	
	// Update is called once per frame
	void Update () {
        setText(title);
	}
   public void setText(string text)
    {
        uitext.text = text;
    }
    public void LoadResource(string resName, string filePath)
    {
        StartCoroutine(LoadResourceCorotine(resName, filePath));
    }
    //產生遊戲物體
    private void CreateGameObject(GameObject go)
    {
        GameObject goPrefab = Instantiate(go, Vector3.zero, Quaternion.identity);
        goPrefab.transform.parent = parent.transform;
        goPrefab.transform.localPosition = Vector3.zero;
    }
    IEnumerator LoadResourceCorotine(string resName, string filePath)
    {
        UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(@"http://212.64.12.155/unity/demo2/AssetBundles/" + filePath);
        yield return request.SendWebRequest();
        AssetBundle ab = (request.downloadHandler as DownloadHandlerAssetBundle).assetBundle;

        GameObject go = ab.LoadAsset<GameObject>(resName);
        prefabDict.Add(resName, go);
        CreateGameObject(go);
        Debug.Log("resName=" + resName + ";goName=" + go.name);
    }

}

在這裏插入圖片描述
4 將Manager腳本掛到GameManager物體上
在這裏插入圖片描述
5 新建一個text作爲prefab,拖到prefabs文件夾,並在右下角設置AssetBundle屬性
在這裏插入圖片描述
好了之後刪除場景中的ABTest

完善我們的lua文件

1 fix.lua.txt

--test
UnityEngine = CS.UnityEngine
UnityEngine.Debug.Log("test")
--version to 1.1
xlua.private_accessible(CS.Manager)
xlua.hotfix(CS.Manager,'Start',function(self)
self.title='Version 1.3'
self:LoadResource('ABTest','ab\\test.ab')
end)

2 fixDispose.lua.txt

--dispose
xlua.hotfix(CS.Manager,'Start',nil)

寫好之後,將這兩個文件上傳到服務器,
比如我的服務器位置爲:http://xxxxx:80/unity/demo2

新建一個AssetBundle打包工具

1 在Assets目錄下新建Editor目錄,新建CreateAssetBundle腳本
在這裏插入圖片描述
2 代碼如下:(注意,博主的環境爲mac,如果你是windows用戶,請更改BuildTarget爲StandaloneWindows)


using UnityEditor;
using System.IO;
public class CreateAssetBundle {
    [MenuItem("Assets/Build AssetBundles")]
    static void BuildAllAssetBundles()
    {
        string dir = "./AssetBundles";
        if(Directory.Exists(dir) == false)
        {
            Directory.CreateDirectory(dir);
        }
        BuildPipeline.BuildAssetBundles(dir, BuildAssetBundleOptions.None,
            BuildTarget.StandaloneOSX);
    }

}

3 回到unity編譯,在Assets目錄下會出現Build AssetBundles菜單
在這裏插入圖片描述
點擊構建,在工程Assets目錄下會出現我們要的ab包
在這裏插入圖片描述
4 將ab包上傳到服務器根目錄

運行及一些bug總結

在這裏插入圖片描述
bugs:
1 如果遇到bug請檢查自己的環境版本
2 請注意路徑是否正確
3 如果報錯,請重新在XLua菜單,重新生成和注入
4 AssetsBundle的構建應該在Xlua環境構建之後,否則會出錯

更多參考

【Unity】場景異步加載的進度條製作

https://blog.csdn.net/sinat_20559947/article/details/50000455

Xlua官網

https://github.com/Tencent/xLua

使用指南

https://github.com/Tencent/xLua/blob/master/Assets/XLua/Doc/hotfix.md

官方FAQ

https://github.com/Tencent/xLua/blob/master/Assets/XLua/Doc/faq.md

菜鳥教程-Lua教程

http://www.runoob.com/lua/lua-tutorial.html

如何評價騰訊在Unity下的xLua(開源)熱更方案?

https://www.zhihu.com/question/54344452/answer/139413144?group_id=800755990562734080

IL(中間語言)

http://blog.csdn.net/dodream/article/details/4726421

玩轉xLua的熱補丁

http://gad.qq.com/article/detail/42303

xlua的配置

https://github.com/Tencent/xLua/blob/master/Assets/XLua/Examples/ExampleGenConfig.cs

更多

1

學習熱更新需要大家到達的程度:

1.什麼是Lua,lua的基本用法與語法。
2.什麼是ab包,ab包的打包,加載,下載。
3.xlua的一些基礎內容,如何開啓一個Lua虛擬機工作壞境,如何加載lua文件,怎樣在c#裏去調lua,在Lua中去調c#。

2 如果有任何問題,可以下方評論,或者加QQ1577432674與本人交流
3 宣傳一下交流羣:在這裏插入圖片描述
4 宣傳一下個人公衆號:edsgame,更多遊戲開發乾貨
在這裏插入圖片描述
5 完整項目工程鏈接(也可以加羣,羣文件有)
鏈接:https://pan.bai刪了我du.com/s/1zUc5L0iUQw5aojXy6a5Ylw 密碼:g8yo

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章