當我們在 Unity 中新增一個腳本 (Script) 時,程式碼中會待有預設的 Start( ) 與 Update( ) 函數,這兩個函數代表的涵義分別是「開始」與「每次更新」
嘗試加入以下程式碼
using System.Collections; using System.Collections.Generic; using UnityEngine; public class HelloWorld : MonoBehaviour { // Use this for initialization void Start () { Debug.Log("Hello World Start!"); } // Update is called once per frame void Update () { Debug.Log("Hello World Update!"); } }
執行後會看到 “Hello World Start!” 的訊息在最一開始被印出了一次
而 “Hello World Update!” 則是不間斷的持續被印出來
Start()
start會在腳本被初始化完成,開始運行的時候「執行一次」,是腳本中最先執行的函數,在start中可以進行變數的初始化、多個腳本中相互關係的設定
Update()
每一幀 ( 每次遊戲畫面刷新 ) 時執行一次,通常用來撰寫遊戲邏輯,如:角色移動、怪物生成、造成傷害等等
延伸閱讀: