Unity Game Dev : Refactoring!

Now, after a few articles, let’s go back to our starting project.
If you remember, we have created a horizontal and vertical input to move the player.

This works, but is not the best thing to do.
First of all, write many lines, expecially “repeat” lines, in the Update method, is not good.
In this moment, nothing bad happen, but we have to start to understand the basic of writing, at least of “good code”.

Remember : there are ALWAYS more than one way to solve problems.

Now, in this two line we control the Y axis value and the Y axis value with Vector3.right and Vector3.up, so, to simplify, we can PASS BOTH in a single Vector3.

Now comment out the upper two line.

If we press Play, the Player works as before without problems, but with less code and a little bit of optimization.

Later in your experience with Unity, we will come across some particular concepts, such as “GARBAGE COLLECTOR” and “OBJECT POOLING”, both of which relate to memory performance.
This is why we should be careful about what and how to code, and optimize the times we use the “new” keyword, especially in the Update method.

If we want optimize better, we create a variable “direction”, store the entire Vector.3 inside it, and pass only “direction” in the transform.Translate();

As we can see, I use another keyword : var.

The Var keyword automatically sets the TYPE of variables. In this case, having created a Vector3, the variable direction is automatically set to the Vector3 type. To confirm this, we hover the mouse over the direction variable

var direction
Vector3 direction
is the same thing

Now, to be clear: some programmers always use “var” keywords, others don’t.
To be honest I have to say that I still don’t know if this is a problem or not.
But I think it’s important to at least be aware of it.

Always in love with programming, even if late (I'm already 39 years old) I decided to follow my dream! We will see how far my passion will take me!