Class methods

A class method is an action or a function. We have seen a few of these so far. Like variables, class methods can use access modifiers to allow or restrict external use. Using no access modifier is the equivalent to setting a method to private:

 [Access modifier] [return datatype] [method-name (parameter list)]  
{ 
       Method Body 
} 

This list will give a simple overview of the pseudo-code example above:

  • Access modifier: public/private/protected
  • Return type: The data type the method returns
  • Method name: A unique, case-sensitive name 
  • Parameter list (or the signature):  Many parameters can be passed into a method; each needs a type and a name
  • Method body: The instructions needed to accomplish the given task

Declaring a method looks a bit like this:

private void ChangeColor(float redcolor) 
    { 

        lbColor.r = redColor; 
        lbColor.g = Random.Range(0, 1f); 
        lbColor.b = Random.Range(0, 1f); 
    } 

In the preceding example (a slight modification of the program's version), we have created a method called ChangeColor. This simple class receives a float, which gets assigned to the redcolor variable. The void keyword means that there is no return type for this method. ChangeColor will only be accessible from within its own class due to the private access modifier.

ChangeColor is a simple method that takes the lbColor variable and randomizes the green and blue elements.

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

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