Methods in Programming

Introduction

In this arti­cle we see what is a method in pro­gram­ming, what they are for and how to declare them in C# lan­guage with con­crete exam­ples in a game project in Unity.

MOST SEARCHED VIDEOS FROM MY CHANNEL

ABOUT UNITY

ABOUT BLENDER

¿What is a Method in Programming?

In this con­text a method is a func­tion that has a set of instruc­tions defined with­in it. 

The method has a name to iden­ti­fy it. 

We can make it require dif­fer­ent type of input data to run. And we can make the method return data as a result.

When we need to exe­cute the instruc­tions con­tained in the method, we do so sim­ply by using its name.

cuadro que describe las propiedades basicas de los metodos en programacion, parámetros, visibilidad
Fig. 1: Scheme illus­trat­ing the basic prop­er­ties of a method.

Modularity

In fig­ure 1 we see the method rep­re­sent­ed as a box, in which the name of the method appears as title, the begin­ning and end of the method is spec­i­fied and the set of instruc­tions is with­in this region.

To under­stand what mod­u­lar­iza­tion is all about, see fig­ure 2. On the left we see a long list of pro­gram­ming instructions. 

Now with­in that list are a num­ber of instruc­tions that are used in more than one place, instruc­tions A, B, C, and D. Let's say these instruc­tions per­form a par­tic­u­lar task and are always exe­cut­ed together.

metodos en programacion, abstraccion y reutilización de código
Fig. 2: On the left a code with repeat­ed instruc­tions. To the right the same code with modules.

Sup­pose we now have to make changes to those instruc­tions (for exam­ple to improve the way it solves the task or add func­tion­al­i­ty), what hap­pens is that we have to iden­ti­fy all the regions where those instruc­tions are.

It would be great if we could change things in one place and the changes apply to all regions where these instruc­tions are used, wouldn't it?

This is pre­cise­ly what we achieve with the meth­ods, they allow us to group sets of instruc­tions in an inde­pen­dent mod­ule that can be called when nec­es­sary, as we can see on the right in fig­ure 2, the instruc­tions were now replaced by the name of the method.

Input and Output parameters

In fig­ure 1 there are arrows that go in and out of the method. With this I try to rep­re­sent the input and out­put of parameters. 

We can make our method require input para­me­ters, which we use inside to make cal­cu­la­tions or per­form any type of task.

In addi­tion we can make the exe­cu­tion of the method pro­duce an out­put data, which we will use out­side the method.

Public and private methods — Visibility

Final­ly in fig­ure 1 we see a nor­mal eye and anoth­er crossed out eye. This rep­re­sents the vis­i­bil­i­ty that the method will have, which is an object-ori­ent­ed pro­gram­ming top­ic, we are not going to delve into this arti­cle but in prin­ci­ple let's say that we can have pub­lic meth­ods and pri­vate methods.

Pub­lic meth­ods can be exe­cut­ed from oth­er Scripts for exam­ple, or we can exe­cute them from a com­po­nent in the hier­ar­chy in Uni­ty, for exam­ple a button. 

Pri­vate meth­ods will not be acces­si­ble from con­texts exter­nal to the script where it is defined.

Syntax

The syn­tax is the set of rules estab­lished in a lan­guage to write the code, in fig­ure 3 we see pos­si­ble syn­tax of a method,

sintaxis de los métodos en programación en java y c#
Fig. 3: Dif­fer­ent com­bi­na­tions of input and out­put para­me­ters for the methods.

This syn­tax can be applied to C# and Java, one detail is that all meth­ods are pub­lic, but we could replace the word "pub­lic" with "pri­vate" and the syn­tax would be correct.

Declaration of a method

Example 1

Let's ana­lyze the method that is above to the left in fig­ure 3.

We have the struc­ture of a pub­lic method that does not require para­me­ters and does not return parameters. 

This struc­ture can be found for exam­ple in the script "Game­Con­trol" of the project My first game in Uni­ty.

We worked on this script in video 4 of the series.

proyecto unity.  codigo c#. metodo perteneciente a una clase que coloca al personaje en una posicion aleatoria del escenario
Fig. 4: Method belong­ing to the script: "Game­Con­trol".

We observe that it has been declared as pri­vate instead of pub­lic, then we find the word "void" with which we indi­cate that this method will not return parameters.

Then the name of the method: "pla­ce­Play­er­Ran­dom­ly".

We open and close paren­the­ses indi­cat­ing that this method does not need parameters.

The begin­ning and end of the method is indi­cat­ed using keys. Inside will be all method instructions.

Invocation or call to the Method

Once the method is defined we can make it run from any part of the script, we can even invoke it from oth­er scripts.

The fol­low­ing fig­ure shows the invo­ca­tion of the "pla­ce­Play­er­Ran­dom­ly" method in the "startGame" method of the same "Game­Con­trol" script.

proyecto unity.  codigo c#. metodo perteneciente a una clase que realiza todas las acciones necesarias para empezar el juego
Fig. 5: In yel­low: invo­ca­tion of the "pla­ce­Play­er­Ran­dom­ly" method. 

To invoke this method we write its name and open and close paren­the­ses, we close the instruc­tion with semi­colon. By doing this we are achiev­ing that all the instruc­tions of the method are executed.

Notice how the names of the meth­ods are already help­ing us to under­stand what is going on. At the begin­ning of the game the char­ac­ter should be placed randomly. 

From the "startGame" point of view the "pla­ce­Play­er­Ran­dom­ly" method is a func­tion that does every­thing nec­es­sary to place the char­ac­ter ran­dom­ly. The startGame method doesn't know exact­ly how it does it but it doesn't care, because pla­ce­Play­er­Ran­dom­ly does its job well.

Example 2

In the upper right cor­ner of fig­ure 3 we have the struc­ture of a method that does not return para­me­ters but does require them to work.

proyecto unity.  codigo c#. metodo perteneciente a una clase que modifica la interfaz gráfica para mostrar el tiempo de la partida
Fig. 6: UIMan­ag­er script "write­Timer" method.

This method requires two para­me­ters to work: an inte­ger val­ue m that will indi­cate the min­utes of the timer and an inte­ger val­ue s that will indi­cate the seconds.

proyecto unity.  codigo c#. metodo perteneciente a una clase que se encarga de añadir segundos al timer
Fig. 7: Invo­ca­tion of the "write­Timer" method from the "Timer" script. 

The invo­ca­tion of this method occurs in sev­er­al places of the code, in par­tic­u­lar the method "addSec­onds" belong­ing to the Script "Timer", this method receives as para­me­ters an inte­ger "s" that rep­re­sents the amount of sec­onds that must be added to the timer because the char­ac­ter grabbed one of the clocks that are on the stage.

The "addSec­onds" method does some oper­a­tions with the "s" vari­able to update the time and final­ly exe­cutes the "write­Timer" method that shows the new time val­ues on screen.

Two obser­va­tions: the first is that since we are exe­cut­ing the method from anoth­er Script it is nec­es­sary to add "uiMan­ag­er". (pay atten­tion to the dot) before writ­ing the name of the method "write­Timer".

The sec­ond is that para­me­ters are entered with­in paren­the­ses and sep­a­rat­ed by comma.

In both scripts I used con­fus­ing names (m and s) on pur­pose so that in the future, when we talk about con­texts, we can ana­lyze them.

Example 3

We move on to meth­ods that return parameters.

The fol­low­ing exam­ple cor­re­sponds to the struc­ture illus­trat­ed in the low­er left cor­ner of fig­ure 3, a method that returns data and does not require para­me­ters to function.

proyecto unity.  codigo c#.metodo perteneciente a una clase que devuelve una posicion aleatoria dentro de una determinada pieza.
Fig. 8: "getRan­dom­Po­si­tion" method of the "Labyrinth­Piece" script. 

The data returned by this method is a "Vector3" and is indi­cat­ed in the dec­la­ra­tion, after the word "pub­lic". Notice that the first line that is not a com­ment says: "Vector3 posi­tion;", there we are declar­ing a Vector3 that we call "posi­tion", then we do some cal­cu­la­tions and at the end of the method we write: "return posi­tion;" indi­cat­ing that we return that Vector3.

This method returns a Vector3 (com­po­nent x,y,z) that rep­re­sents a ran­dom posi­tion belong­ing to the inside of a giv­en piece of labyrinth. In this way we can use this posi­tion to place the pedestal or clocks with­out wor­ry­ing for exam­ple that they are embed­ded in a wall.

proyecto unity.  codigo c#. llamado del metodo que devuelva una posicion aleatoria del escenario
Fig. 9: Invo­ca­tion of the "getRan­dom­Po­si­tion" method. 

It is not easy to under­stand the instruc­tion high­light­ed in fig­ure 9. For now let's look at two things, the first is that we make a call to the "getRan­dom­Po­si­tion" method using its name (as seen at the end of the instruc­tion). The sec­ond is that the result of that invo­ca­tion is a Vector3 data, there­fore, using the equal sign, we assign it to the "rP" data that is defined as Vector3.

Example 4

The last exam­ple cor­re­sponds to the struc­ture illus­trat­ed in the low­er right cor­ner of fig­ure 3, a method that returns data and requires para­me­ters to function. 

proyecto unity.  codigo c#. metodo para comparar las puntuaciones de los jugadores
Fig. 10: Dec­la­ra­tion of the "isBestScore" method. 

We see that in the dec­la­ra­tion we say that the method "isBestScore" returns a bool type data and requires an int type data that we call "val".

If you want to know a lit­tle about prim­i­tive data I invite you to read this arti­cle about vari­ables or watch this video.

The "isBestScore" method returns a vari­able that can be true or false. The util­i­ty of this method is that we use it to ask if the score obtained in the game (val) is bet­ter than the one saved so far (bestScoreVal­ue).

proyecto unity.  codigo c#. utilizacion del metodo para comparar las puntuaciones de los jugadores
Fig. 11: Invo­ca­tion of the "isBestScore" method. 

This method is invoked in the "game­Won" method. Since the method returns a bool val­ue, we can use it direct­ly as an argu­ment for an if state­ment, because "score.isBestScore(time)" is equiv­a­lent to hav­ing a true or false value.

StartGame() Mehotd from GameControl

To fin­ish fig­ure 12, the "startGame" method is observed along with the oth­er meth­ods it invokes.

In addi­tion to group­ing instruc­tions, a method must have a well-estab­lished pur­pose that is con­sis­tent with the name we gave it, so that we can quick­ly know what its func­tion is and what type of instruc­tions it may contain.

proyecto unity.  codigo c#. esquema de la ejecucion del juego, metodo startGame
Fig. 12: Dec­la­ra­tion of the "isBestScore" method. 

For exam­ple, the "startGame" method is in charge of coor­di­nat­ing a series of actions to start the game, but it is not he who direct­ly per­forms these actions, but invokes oth­er meth­ods with more spe­cif­ic tasks.

This makes it eas­i­er for us to make changes to the code and debug errors.

Conclusion

Meth­ods are a pow­er­ful tool for devel­op­ing spe­cif­ic, effi­cient, reusable and sus­tain­able solutions. 

Sus­tain­able in time because at all stages of devel­op­ment we will have to make changes, so we have to be able to remem­ber or quick­ly under­stand how our code works.

This is achieved by using descrip­tive names, doc­u­ment­ing our code, and apply­ing the object-ori­ent­ed paradigm.

Scroll to Top
Secured By miniOrange