The PlayerInput component
- Game Development course
- Advanced
- Lesson 57/71
- 4 min
Learn to listen to actions with the PlayerInput component.
The PlayerInput component
The PlayerInput component attaches an Input Action asset to a GameObject: you drag the .inputactions file into the Actions field and pick the starting Action Map with Default Map. The Behaviour field decides what happens when an action triggers; with Send Messages the action name gets On in front and that method is called.
PlayerInput pi = GetComponent<PlayerInput>();
Debug.Log("Harita: " + pi.defaultActionMap);So for a Jump action it is enough to write an OnJump method.
Reading values with InputValue
The callback method receives an InputValue; this object carries the current value of the action. You read it with value.Get<T>(): a Vector2 inside OnMove, a float for trigger-like actions.
public void OnMove(InputValue value)
{
Vector2 h = value.Get<Vector2>();
Debug.Log("Hareket: " + h);
}Whenever the action fires, PlayerInput calls the matching method.
Practice Write the callback methods
Write a MonoBehaviour named OyuncuGirdisi. Add a Vector2 field called hareket. In OnMove(InputValue value) assign value.Get<Vector2>() to the hareket field. In OnJump(InputValue value) call Debug.Log("Zipla!"). In Start call Debug.Log("Girdi dinleniyor").
Starter code
using UnityEngine;
using UnityEngine.InputSystem;
public class OyuncuGirdisi : MonoBehaviour
{
Vector2 hareket;
void Start()
{
Debug.Log("Girdi dinleniyor");
}
// OnMove metodu InputValue alir, Vector2 degerini hareket alanina atar
// OnJump metodu InputValue alir ve ziplama mesaji basar
}Sample solution
using UnityEngine;
using UnityEngine.InputSystem;
public class OyuncuGirdisi : MonoBehaviour
{
Vector2 hareket;
void Start()
{
Debug.Log("Girdi dinleniyor");
}
public void OnMove(InputValue value)
{
hareket = value.Get<Vector2>();
}
public void OnJump(InputValue value)
{
Debug.Log("Zipla!");
}
}Expected output
Girdi dinleniyor
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 In Send Messages mode, which method is called when the Jump action triggers?
- OnPress(InputValue value)
- HandleJump(InputValue value)
- JumpInput(InputValue value)
- OnJump(InputValue value) Correct answer
Explanation: Send Messages puts On in front of the action name and looks for that method; the Jump action calls OnJump, and the method takes an InputValue parameter.
2 Read the Move value as Vector2
Vector2 h = value.Get____();
Vector2 h = value.Get<Vector2>();
Explanation: The Move action gives a two-dimensional value, so the Get call takes the Vector2 type.
3 PlayerInput fields
| Term | Meaning |
|---|---|
Actions |
The .inputactions file in use |
Default Map |
The Action Map active at startup |
Send Messages |
The behaviour calling the On... methods |
Invoke Unity Events |
Binding functions through the Inspector |