Unity new Input System : Tips to create a “clean” Player Input System(Part XI)
We have seen many feature that new Input System implements.
Now we try to extend this a little bit.
In a real game, how can we implement this new System in a sort of “modular” way?
One way, and personally I think is a good way, is to have a Player_Manager who manage the Input of Player, and the Player Class has the “real implementation” of what to do.
In this example I create a Input Actions from scratch, and I called it GameInput.
As we had learning from the beginning of our journey, name convention is really important.
Not only in variables or Functions / Methods, but for everything.
So, the chooise to call the Input Action “GameInput”, it means we have a generic input for our game. And we probably have more Classes, for example Player, that we manage only the Input for the Player, and so on.
Let’s go to Unity to see this in action.
Here we create an empty GameObject, and we called it Player_Manager.
Then we create a simple cube or sphere, called it Player, and make it children of Player_Manager.
To make everything clean, in Assets we create an Input folder and the Scripts folder.
Inside Input folder we create the GameInputActions, and Generate the C# Class.
In the Scripts folder, we create Player Class and PlayerManager Class.
Now, we try to divide the RESPONSIBILITY of this two Classes, one for Implementation, one for manage the Input.
How can we do?
Let’s start with Player_Manager.
Inside here, we take the reference to the GameInput.
And of course we initialize it as usual.
Furthermore, we create “InitializeInput” method, and we call it in Start().
And because this is a Player_Manager, we need a reference to the “real” PLayer.
We Serialize it so we can drag and drop it in the Inspector.
And in the Player_Manager, we MANAGE the Inputs.
So we create the Update Method, and inside we write the inputs.
At this point, how do we use the “move” variable?
Remember what we try to do here?
A Class manages the Inputs, a Class implements the Inputs.
So now let’s go into the Player Class and write some code to implement the movement.
Probably we need a _speed variable
And now we create a Move() method.
And we pass inside it a local variable Vector2 “direction”, so we can call it inside the Player_Manager Class, and pass our “move” variable.
And if we test it
It works perfectly.
This is obviously one of the MANY WAYS we can do it, as always, this isn’t the only one and I’m sure it’s not the best, but it works really well for me, and sharing the responsibility of the Classes is always a good way to code.
Because if we have any problems, we know exactly where to look.
We do not underestimate this type of thing, as programmers many times we have and will have problems of this type, but if we look for a problem and we know exactly where it can be, it makes our job not easy, but it simplifies it