Defining a method the right way

Just as with variables, we have to let Unity know about a method before we can use it. Depending on who you talk to, some will say "We have to declare a method," others will say "We have to define a method," or even "We have to implement a method." Which is correct? In C#, it doesn't make any difference. Use whichever term helps you learn more easily. I like to say I'm defining a method's code block, nothing like declaring a simple variable on a one-line statement.

The minimum requirements for defining a method

There are three minimum requirements for defining a method:

  • The type of information, or data, that a method will return to the place from where it was called
  • The name of the method should be followed by a pair of parentheses
  • A pair of curly braces should be present to contain the code block:
    returnDataType  NameOfTheMethod ( )
    {
    
    }

Looking at LearningScript once again, or any Unity-generated script, you can see that the Start() method has the three minimum requirements for a method:

void Start ()
{

}

Here's what we have:

  • Our first requirement is the type of data that the method will return to the place in the code that called this method. This method isn't returning any value, so instead of specifying an actual type of data, the void keyword is used. This informs Unity that nothing is being returned from the method.
  • The second requirement is the method name, which is Start().
  • The last requirement is the curly braces. They contain the code that defines what the method is going to do.

This example fulfills the bare minimum requirements for a method. However, as you can see, there's no code in the code block, so when Start() is called by Unity, it doesn't do anything at all. Yet it's a method. Normally, if we aren't going to use a method by adding code to a skeleton method created by Unity, we can simply remove them from our script. It's normally best to remove unused code after the script has been written.

Here's what we know about this bare-minimum method definition as far as Unity is concerned:

  • There's no public modifier, which means that this method is private by default. Therefore, this method cannot be called from other scripts.
  • There's no code in the code block. Therefore, this method doesn't do anything. So, it can be removed if we wish to remove it.

Note

Methods that do not return any data use the void keyword instead of datatype.

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

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