剛開始學Unity的時候,最難搞定的就是這兩個functions的差別,依照官方文件所描述的:this
Awake(): Awake is called when the script instance is being loaded.spa
Start(): Start is called just before any of the Update methods is called the first time.component
Awake()跟Start()差在哪?orm
習慣C++人來講,這根本是「小三」的顛倒!爲何要這樣分搞不懂。後來寫久了遇到問題了才瞭解原來繼承MonoBehaviour的class:blog
Awake() == C++的Construct繼承
Start() == 程式啓動後第一個會被忽叫的functionip
進一步想,咱們在寫C++的class時,不也有時候會本身寫Init()的Member Fucntion嗎?因此Start()也可想成自訂的Init()就好!ci
在使用上的基本原則就是,若是你有class的member參考其它Component,就在Awake裏設定好,例如:開發
1it |
void Awake () { |
2 |
|
3 |
thisTrans = transform; |
4 |
|
5 |
item = GetComponent(); |
|
|
7 |
} |
這是確保當咱們在Start()裏須要呼叫member所參考component中的function時,這個參考已經創建而非NULL。固然你也能夠說你在Start()的一開始先作GetComponent的動做,這也是OK的。不過開發到後來系統class彼此間的連結愈來愈強時,因該就會慢慢體會到Awake()的重要,由於Unity裏物件的創建順序沒法控制,因此保險一點仍是將GetComponent這件事留在Awake比較好一點。