Now we continue the explanation and talk about RETURN methods.
Take again the Sum() example
In this case we make the method PUBLIC, but we can make it PRIVATE.
Just like variables, the method can be called or read outside our Player: public makes it possible while private makes it readable ONLY inside the Player.
This logic is exactly the same.
Now, we talk for one moment about keyword “VOID”.
In easy way, void means the method don’t return nothing.
It simply execute the logic inside the curly brackets.
Look at this :
Inside Sum method I write the two variables, create a total and with Debug.Log I print it.
This is exactly what you are thinking!
I cut and paste from Start to this method.
So now, i CALL this method in Start and voilà, same result!
In fact, after I press Play
We create our methods for many reasons, one of them being that we can get a clear picture of what is going on in our code. We can LITERALLY READ what’s going on in our game, application, etc.
Is clear and is better to understand, also in both Start and Update it is good practice not to leave lines of code, each function must have its own method. For example, do we need to add two numbers? Well, let’s create our own method of doing it.
Now, talk a little bit about VOID keyword.
In this case, for make things easy, I have create a void Sum method to, well, sum two numbers.
Think about it: we have the numbers.
And we want Sum that numbers right?
So why not create an INT method and that returns the total to us?
Sounds really difficult, right? It is actually much simpler than expected!
The only real difference is this :
Litlle advice : as we can see, now there is a RED UNDERLINE.
This happen because we can’t give the method same name.
There is actually a way, called OVERLOAD, but let’s take it one step at a time.
So, for now i delete the first Sum method andpass the data inside the return method
Even if I delete it, the RED UNDERLINE is not gone.
Well, since we created an INT method, not VOID, we need to give a RETURN PATH to this type of method.
It means this : we pass the numbers into the method and we want the method to RETURN the result to us.
Don’t worry, is not so complicated.
For make RED UNDERLINE disappear, we need another keyword call “RETURN”.
The method has to return us something, so we use return keyword to make it.
This is the syntax
Another tips : we have a total variable, which return us a + b, ok?
But we don’t necessarily need a variable to hold the result.
We could write this too
The result is always a + b, right?
The total variable is something maybe we need, maybe not, it depends from what we doing ok?
The important thing is the logic : pass numbers in the method which RETURN the result.
In the next session of method we talk about methods’ PARAMETERS! This is an important part, and before go down and create our game we need to know very well!
See you soon!!