Migrating to the new Unity Input system
I'm migrating over to the new Unity Input system and I've gotten it to a reasonable point.
Currently WASD/Arrow keys move the camera rig transform about and it works as expected:
if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow))
{
_newPosition += (transform.forward * movementSpeed);
}
For the new input system I have setup all of the prerequisite assets, action maps, actions and bindings. I have a "Pan" action which is set up as a 2D Vector composite and I have set up bindings for up, down, left, right which are mapped to w, s, a, d respectively.
The actions are enabled and and I have a performed
and canceled
handler which both call a function called HandlePan
which sets a Vector2
called _newPosition
.
The new code, which directly replaces the Input.GetKey
code above looks like:
if (_panAxis.y > 0)
{
_newPosition += (transform.forward * movementSpeed);
}
This all works as expected, but I am doubting myself and I want to make sure I'm doing it right, or whether there is a different approach that is recommended.
Thanks!
Answer by chris_gamedev · Jan 07, 2021 at 12:51 PM
So, the important thing here is that with the new input system there is essentially two main concepts. Event based and polling based.
The old Unity Input system relies heavily on polling, e.g. "is this key held down right now / was this key pressed this frame / was this key let go this frame".
The new system allows you to use events, e.g. performed
and canceled
. These very much have a place but for my use case this was the wrong route to go down.
The new code, rather than being accessed in an event pattern we can poll for it in Update() when it is needed.
Vector2 panAxis = _controls.CameraRig.Pan.ReadValue<Vector2>();
_newPosition += (transform.forward * (_movementSpeed * panAxis.y));
_newPosition += (transform.right * (_movementSpeed * panAxis.x));
Your answer
![](https://koobas.hobune.stream/wayback/20220613022808im_/https://answers.unity.com/themes/thub/images/avi.jpg)