Game Development
C# generated class
Learn to read actions with the auto-generated C# class.
The Generate C# Class option
If you tick Generate C# Class in the Input Action asset's Inspector, Unity produces a C# class named after the asset. The generated class exposes actions as properties; for example inputActions.Player.Jump is an InputAction object.
PlayerInputActions inputActions = new PlayerInputActions();
inputActions.Player.Enable();
Debug.Log("Eylemler aktif");
Attaching a method to its performed event with += gives you a compile-time checked wrapper.
started, performed and canceled
An action has three events: started when the input begins, performed when the action really fires, and canceled when the input is released. You add the subscription in OnEnable and remove it in OnDisable, so the links are cleaned up when the object is disabled.
void OnEnable()
{
inputActions.Player.Jump.performed += OnJump;
}
void OnDisable()
{
inputActions.Player.Jump.performed -= OnJump;
}
The event method takes an InputAction.CallbackContext.
Exercise Set up the subscription
Write a MonoBehaviour named OyuncuKontrol. Add a PlayerInputActions field called inputActions and create it in Awake with new PlayerInputActions(). In OnEnable attach the OnJump method to the inputActions.Player.Jump.performed event; in OnDisable remove the same link. The OnJump method takes an InputAction.CallbackContext ctx and calls Debug.Log("Zipla!"). In Start call inputActions.Player.Enable() and print Debug.Log("Eylemler aktif").
Show example solution
using UnityEngine;
using UnityEngine.InputSystem;
public class OyuncuKontrol : MonoBehaviour
{
PlayerInputActions inputActions;
void Awake()
{
inputActions = new PlayerInputActions();
}
void OnEnable()
{
inputActions.Player.Jump.performed += OnJump;
}
void OnDisable()
{
inputActions.Player.Jump.performed -= OnJump;
}
void OnJump(InputAction.CallbackContext ctx)
{
Debug.Log("Zipla!");
}
void Start()
{
inputActions.Player.Enable();
Debug.Log("Eylemler aktif");
}
}
Test yourself
-
How do you subscribe to an action's event in the generated class?
- inputActions.Player.Jump.performed += OnJumpMethod
- InputAction.actionFound += OnJumpMethod
- Jump.OnPress += OnJumpMethod
- playerInput.OnJump += OnJumpMethod
Show answer
inputActions.Player.Jump.performed += OnJumpMethod — In the generated class every action is an InputAction; the performed, started and canceled events accept methods with +=.
-
Remove the subscription
inputActions.Player.Jump.performed ____;
Show answer
inputActions.Player.Jump.performed -= OnJump;
-
Generated class concepts
- Generate C# Class
- The option that produces a C# class
- Wrapper
- Class exposing actions as properties
- performed
- The moment the action fires
- CallbackContext
- The data the event method receives
Next lesson: Gamepad support