官术网_书友最值得收藏!

The Start(), Update(), and Awake() methods and the execution order

The Start(), Update(), and Awake() methods are called automatically. The Start() method is called on the frame when the script is enabled. For most of our components, this will be when you press the Start button in Unity.

The Awake() method is called just before the Start() method. That gives a very convenient place to set up code if you have any. The Update() method is very specific. It's called on every frame if the component is enabled. It's very useful for observing user keyboard actions, for example. As you can see in our script, in Line 16, we are checking on every frame to know whether the user has pressed the Enter key.

Let's create a new C# Script and call it LearningMethods. As you can see, the Start() and Update() methods are added automatically when you create a new script. To test them all, all that we need to do is add the Awake() method and a few other useful lines to print something on the Console panel.

As you already know, our three methods should be called in a very specific order. Add the LearningMethods component to some GameObject in the Unity scene and press Play. Then stop after 2 seconds. Keep an eye on the Console tab:

Wow! A lot of stuff on the Console tab? Why? Scroll up to the very top of the Console list. We can observe that Unity has printed the Debug:Log information from our Awake() method, followed by the Start() method. Then the madness starts. Unity prints tons of messages from the Update() method. We know why! Update() is called on every frame, so Unity will execute the lines of code within Update() forever, for every frame it renders.

You can, of course, print other information to Console—not just messages. Replace line 18 with this line:

Debug.Log(Time.time);

Press Play in Unity. You will notice that the time, in seconds, is printed, after you have pressed Play button. It's fun, isn't it? Maybe not. Don't worry; we will get into much more interesting programming after we cover dot syntax.

主站蜘蛛池模板: 崇左市| 澄江县| 内江市| 天水市| 西安市| 彭泽县| 漯河市| 云龙县| 五原县| 云安县| 禄劝| 六安市| 略阳县| 巩留县| 太仆寺旗| 凤庆县| 若羌县| 葫芦岛市| 前郭尔| 桐乡市| 西丰县| 常德市| 漳州市| 宝清县| 黄石市| 石狮市| 仪征市| 商都县| 陈巴尔虎旗| 如皋市| 冀州市| 永胜县| 博爱县| 衡南县| 静安区| 葵青区| 岳阳县| 怀来县| 阳西县| 富裕县| 大竹县|