Understanding parentheses – why are they there?

One thing for sure is that parentheses make it easy to recognize that it's a method, but why are they part of a method's name?

We already know that a method is a code block that is going to be called multiple times. That's one of the reasons a method is created in the first place—so that we don't have to write the same code over and over. Remember the AddAndPrintTwoNumbers() example method? We have mentioned that a method can take some input parameters. Why is this useful?

A script may need to add two numbers several times, but they probably won't always be the same two numbers. We can have possibly hundreds of different combinations of two numbers to add together. This means that we need to let the method know which two numbers need to be added together at the moment when we call the method. Let's write a code example to make sure you fully understand it:

Understanding parentheses – why are they there?

Lines 7, 8, and 9 should be quite clear to you—simple declarations of variables.

Let's take a look at the AddAndPrintTwoNumbers method. It's a void function. Again, this means the function does something but does not return any data. Inside the parentheses, our method takes two variables: firstNumber and secondNumber.

Line 25 contains the declaration and assignment of the local variable that we will be printing on line 26.

So, AddAndPrintTwoNumbers is written the universal way. We can reuse this function as many times as we want, passing different parameters.

Lines 15, 16, and 17 call our function three times, each time passing different parameters to the function. Let's test whether it works! Go ahead, add the LearningReusableMethods component to any GameObject in the Unity scene, and click on Play.

As this script executes, the AddAndPrintTwoNumbers method is called three times on lines 15, 16, and 17. The method's code block adds two numbers and displays the result in the Unity Console tab:

Understanding parentheses – why are they there?

As expected! The console will print out the values. There's a special name for information between the parentheses of a method definition, such as line 23—the code is called method parameters.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset