Asked a question yesterday what is the difference between Monobehaviour's awake () and start ()?
Of course awake () will be called before start (), as the Earth Man knows. If it's just a sequential problem, then of course there's not much need for two functions. Take a closer look at the API documentation:
- Awake (): Awake is called when the script instance is being loaded.
- Start (): Start is called on the frame when a script was enabled just before any of the Update methods is called the first Ti Me.
OK, from the documentation we see the difference between the two:
Awake () is called when the script object is instantiated, and start () is called at the first frame of the object, and before update ().
To make this clearer, let's do a little experiment and write a script to dynamically create another script object:
Using unityengine;using system.collections;public class tryobject:monobehaviour{ //Use this for INITIALIZATION
void Start () {#if true gameobject Dynago = new Gameobject ("Dynamicgo"); Dynago.addcomponent<dynamicobject> (); #else Object prefab = resources.load ("Dynamicgo"); Object instance = gameobject.instantiate (prefab); #endif }}
Another script will write a few empty functions to break the point:
Using unityengine;using system.collections;public class dynamicobject:monobehaviour{ void Awake () { }< c11/>//use of the initialization void Start () { } //Update is called once per frame void UPDA Te () { }}
The following is the call stack for Dynamicobject:awake () when using the AddComponent () method:
Here is the call stack for Dynamicobject:awake () when using the load Prefab method:
The following is the call stack for Dynamicobject:start ():
In this case, the previous conclusion is more definite. In use, there are a few points worth noting:
- Some members of the script must be written in awake () if they want to use it immediately after the creation of the Code;
- When the level is loaded, the awake order of the script is not controllable, and when the level is loaded, the object instantiation and the Awake () call relationship, it depends on the source code to know.
The essential difference between awake () and start () in a Unity3d script