五邑隱俠,本名關健昌,12年游戲生涯, 本教程以 Unity 3D + VS Code + C# + tolua 為例,
一、啟動腳本
第一篇 “搭建開發環境”,在 “配置 Lua 開發環境” 一節提到,把 tolua 下的 Assets、Luajit、Luajit64、Unity5.x拷貝到工程根目錄,簡化 C#、Lua 互調,
先打開 Assets/Lua/Main.lua ,加上 OnUpdate() 方法(第6~8行)
1 --主入口函式,從這里開始lua邏輯 2 function Main() 3 print("logic start") 4 end 5 6 function OnUpdate() 7 print("Lua OnUpdate") 8 end 9 10 --場景切換通知 11 function OnLevelWasLoaded(level) 12 collectgarbage("collect") 13 Time.timeSinceLevelLoad = 0 14 end 15 16 function OnApplicationQuit() 17 end
新建目錄CSharp用于存放C#腳本,新建一個C#腳本 Main.cs 作為啟動腳本
1 using UnityEngine; 2 using LuaInterface; 3 4 public class Main : LuaClient 5 { 6 private LuaFunction updateFun = null; 7 8 // Start is called before the first frame update 9 void Start() 10 { 11 // bind OnUpdate 12 this.updateFun = luaState.GetFunction("OnUpdate"); 13 } 14 15 new void OnApplicationQuit() 16 { 17 this.updateFun.Dispose(); 18 this.updateFun = null; 19 20 base.OnApplicationQuit(); 21 } 22 23 // Update is called once per frame 24 void Update() 25 { 26 this.updateFun.Call(); 27 } 28 }
1、在Unity里,場景由GameObject組成,加載場景,會創建場景中的GameObject,
2、GameObject可以添加組件,組件基類為Component,但用戶自定義的腳本都繼承自MonoBehaviour(Component的子類)
3、Main類繼承 LuaClient,LuaClient 繼承 MonoBehaviour,所以 Main.cs 腳本可以作為組件添加到場景的 GameObject上,
4、組件有幾個關鍵的生命周期:
1)Awake:只呼叫一次,在組件整個生命周期開始時呼叫,組件一般不建議寫構造方法,需要提前初始的資料,可以在Awake初始化
2)Start:第一次Enable時呼叫,整個生命周期只呼叫一次,可以在這里初始化組件資料
3)Update:每幀呼叫一次
4)OnApplicationQuit:游戲退出時呼叫
5、LuaClient 在 Awake 里 初始化 Lua 環境,系結C#類到Lua,然后加載 Assets/Lua/Main.lua 檔案,并呼叫其中的 function Main() 方法,開始 Lua 邏輯,
6、luaState 是 LuaClient 的一個LuaState型別欄位,保存 Lua 虛擬機物件,LuaState.GetFunction 獲取 Lua一個回傳LuaFunction型別的全域方法,第12行獲取Lua 的 OnUpdate 方法,該方法在 Assets/Lua/Main.lua 里定義
7、LuaFunction.Call() 執行該Lua方法,第26行,組件Main每次 Update 時都 呼叫 Assets/Lua/Main.lua 的 OnUpdate 方法,驅動 Lua 邏輯更新,
二、Unity3D編輯器簡介
1、層級管理面板
顯示場景中所有的 GameObject,可以快速選中場景中的 GameObject

2、場景編輯面板
可視化編輯場景中GameObject位置

3、預覽面板
預覽場景運行的效果

4、屬性面板
展示 GameObject 添加的組件,以及組件的屬性,如圖中選中 Main Camera 后顯示該GameObject 的組件有Transform、Camera組件

5、工程面板
工程的資源倉庫(腳本也是資源),用于搭建場景的零部件:腳本、聲音、圖片、預制體、場景等

三、添加啟動腳本到場景
1、在工程面板選擇Scenes檔案夾,默認3D工程會生成一個SampleScene,如果沒有,可以手動創建一個,雙擊這個場景圖示,會打開該場景

2、在層級管理面板選擇 Main Camera 這個 GameObject

3、在屬性面板下方,點擊 Add Component 按鈕,選擇 Scripts --> Main,這樣場景運行時,Main腳本就會開始它的生命周期

4、作為啟動腳本,我們希望它比其他腳本優先執行,在工程面板選擇CSharp檔案夾,選中Main腳本

5、在屬性面板右上方,點擊 Execution Order 按鈕

6、添加Main腳本,并調整其順序在 Default Time 之前

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/412994.html
標籤:其他
