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

Method names are substitutes, too

You learned that a variable is a substitute for the value that it actually contains. Well, a method is no different. Take a look at line 20 in the previous screenshot:

void AddTwoNumbers () 

AddTwoNumbers() is the name of the method. Like a variable, AddTwoNumbers() is nothing more than a named placeholder in the memory, but this time, it stores some lines of code instead. So, wherever we want to use the code in this method in our script, we just write AddTwoNumbers() and the code will be substituted.

Line 20 has an opening curly bracket and line 23 has a closing curly bracket. Everything between the two curly brackets is the code that is executed when this method is called in our script. Look at line 16 from the previous screenshot, precisely at this part:

AddTwoNumbers(); 

The method named AddTwoNumbers() is called. This means that the code between the curly brackets is executed. Of course, this AddTwoNumbers() method has only one line of code to execute, but a method can have many lines of code.

Line 22 is the action part of this methodthe part between the curly brackets. This line of code adds the two variables and displays the answer on the Unity Console.

Then, follow these steps:

  1. Go back to Unity and have the Console panel showing
  2. Now click Play

Oh no! Nothing happened! Hold on... Actually, as you sit there looking at the blank Console panel, the script is running perfectly, just as we programmed it. The first part of line 16 in the script is waiting for you to press the Enter key. Press it now.

And there you go! The following screenshot shows you the result of adding two variables that contain the numbers 2 and 9:

In our LearningScript, line 16 waited for you to press the Enter key. When you do this, the AddTwoNumbers() method is executed. When you do this, line 17, which calls the AddTwoNumbers() method, is executed. This allows the code block of the method, line 23, to add the values stored in the number1 and number2 variables.

While Unity is in the Play mode, select Main Camera so that its components appear in the Inspector panel. In the Inspector panel, locate variableScript and its two variables. Change the values, currently 2 and 9, to something else. Make sure that you click on the Game panel so that it has focus. Then press the Enter key again. You will see the result of the new addition in Console.

You just learned how a method works to allow a specific block of code to be called in order to perform a task. We didn't get into any of the wording details of methods here. This was just to show you fundamentally how they work. We'll get into the finer details of methods in a later chapter.

主站蜘蛛池模板: 上栗县| 肥东县| 封丘县| 永康市| 宁阳县| 都兰县| 连州市| 定襄县| 刚察县| 盘锦市| 吴江市| 鲜城| 沭阳县| 陵川县| 通州区| 中超| 张家口市| 宁波市| 盐山县| 潢川县| 大丰市| 武清区| 兴业县| 新安县| 大安市| 陆川县| 鄂托克前旗| 叶城县| 孝感市| 金寨县| 克山县| 竹北市| 上饶市| 佛学| 佳木斯市| 沙坪坝区| 嘉定区| 沅陵县| 聂荣县| 台安县| 伊金霍洛旗|