Search Unity

How do I check if an InputAction has been performed at a certain frame in the Update() function?

Discussion in 'Input System' started by matijas_05, Oct 12, 2018.

  1. matijas_05

    matijas_05

    Joined:
    May 8, 2017
    Posts:
    11
    In the wiki it says that you can check in the Update() function if an action has been performed at a certain frame by accessing the 'hasBeenPerformedThisFrame' property, but I can't find it on an InputAction object. Is it still possible to somehow do that?
     
  2. Rene-Damm

    Rene-Damm

    Joined:
    Sep 15, 2012
    Posts:
    1,779
    Not out of the box. The problem is that state aggregation works badly for actions. Their model isn't frame-based but rather goes from state change to state change. So, even if there's multiple button presses or stick motions in the same frame, an action still catches every single change.

    A polling-based API that goes frame to frame is more difficult to model onto this than for controls. A control like Gamepad.leftStick is just a value whereas an action has complex state.

    One relatively easy way to get once-per-frame behavior is with a pattern like this:

    Code (CSharp):
    1. public InputAction myAction;
    2. private bool m_MyActionHasBeenPerformed;
    3.  
    4. public void Awake()
    5. {
    6.     myAction.performed += ctx => m_MyActionHasBeenPerformed = true;
    7. }
    8.  
    9. public void Update()
    10. {
    11.     if (m_MyActionHasBeenPerformed)
    12.     {
    13.         //...
    14.         m_MyActionHasBeenPerformed = false;
    15.     }
    16. }
    17.  
    18.  
    There's still some work to be done on the API. Eventually, you won't have to manually fuss around with delegates in most setups.