Game Development
The PlayerInput component
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.
Exercise 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").
Show example 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!");
}
}
Test yourself
-
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)
Show answer
OnJump(InputValue value) — 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.
-
Read the Move value as Vector2
Vector2 h = value.Get____();
Show answer
Vector2 h = value.Get<Vector2>();
-
PlayerInput fields
- 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
Next lesson: C# generated class