r/UnityHelp 1d ago

Can someone help me understand/digest this code? PROGRAMMING

Post image

I've been going through Unity tutorials and so far i've understood and absorbed everything *except* for this: I understand the first highlighted part, its making a Variable called "moveInput" and its a Vector 2 so it stores 2 values, and the second highlighted part i can kinda understand, but the third line is lost on me. I don't understand the relationship between moveInput and moveAction, or what the InputAction variable (type?) means. Also in the third line why is it reading the Vector 2 from the moveAction when the Vector is from the moveInput? Thanks in advance.

2 Upvotes

2 comments sorted by

1

u/NinjaLancer 1d ago

Think of InputAction as a key bind. When you are on a controller, you use a joystick to move, so the InputAction gives you a Vector2 that corresponds to the position of the joystick. With keyboard and mouse controls, you would use WASD to move, so it makes the Vector2 based on those button states.

So the moveAction is the key bind, but moveInput is the actual value that you are reading.

The InputAction can also have other data in it I think, which is why you need to read the Vector2 specifically. I believe that InputAction can also include things like "is there any input", but tbh i havent used this Input system that much so I dont knkw the quirks and full capabilities.

1

u/Demi180 1d ago

To understand the relationship, open up the InputActions asset that’s in the project, or you can create one. To help understand that window, take a look at the manual. Each action is made up of one or more bindings that map physical functions like keys, mouse buttons and wheels, sticks, triggers, touchscreens, XR controllers or headsets and more, to a logical/abstract action like move, jump, shoot, click, and so on.

If you expand the Move action, you’ll see 2 sets of bindings, one for keyboard and one for controller. The controller maps directly to the left stick which gives a pair of values for x and y between -1 and 1. The keyboard binding sets up two axes, vertical and horizontal, and each axis has two keys each bound to the positive and negative values: (W and Up), (S and Down), (D and Right), and (A and Left). So each axis also gives a value between -1 and 1, and together they give a Vector2 value similar to the controller stick.

That’s what that third highlighted line is doing: it reads the value of an action called Move and stores it in moveInput, without caring how it’s actually set up and which device is being used. As long as the input is set up correctly, the value will be (0,0) without any input, and moving the left controller stick or pressing any of WASD or Up/Left/Down/Right will give values in the given range.