Search Unity

  1. We are migrating the Unity Forums to Unity Discussions by the end of July. Read our announcement for more information and let us know if you have any questions.
    Dismiss Notice
  2. Dismiss Notice

Question Input Action held down for X seconds (repeatable multiple times)

Discussion in 'Input System' started by aegishua, Jan 15, 2021.

  1. aegishua


    Jul 11, 2020
    Hey guys, I've just been googling and reading around this forum for a few hours so i thought I'd post a question while I keep scouring various pages for an answer.

    Alright the scenario is I've got a turn based combat system and I'm trying to build an end turn interaction similar to that found in Divinity 2.

    For those that haven't played it or seen this interaction, the player just has to hold the (B) button on the gamepad until the red ring around the icon fills up (i.e. hold (b) for two seconds). This can be done multiple times whenever it is a player character's turn.

    Now I've been trying to replicate this behaviour using the new InputSystem but I haven't been able to do it for some reason. Basically after the following code procs once it no longer registers anymore and it appears this is by design.

    Code (CSharp):
    2.            var endTurnAction = map.AddAction(
    3.                 "combat-end-turn",
    4.                 binding: "<Gamepad>/b",
    5.                 interactions: "hold(duration=2)"
    6.             );
    8.             endTurnAction.performed += (context) =>
    9.             {
    10.                 if (context.interaction is HoldInteraction hi)
    11.                 {
    12.                        // Perform the end turn action here. This will only ever trigger once.
    13.                 }
    14.             };
    The closest I've gotten is tracking the started and cancelled of an action and storing a variable to determine the time before lifting the key:

    Code (CSharp):
    2.             float startTime = 0;
    3.             endTurn.started += (context) =>
    4.             {
    5.                 startTime = Time.time;
    6.             };
    8.             endTurn.canceled += (context) =>
    9.             {
    10.                 // IF we cancelled after 2s (let go of the key)
    11.                 if (startTime != 0 && startTime - Time.time > 2)
    12.                 {
    13.                     // Perform something  
    14.                 }
    16.                 startTime = 0; // Reset
    17.             };
    However, the downside to this approach is that after 2 seconds of holding down the button nothing happens (i.e. you can hold down the button indefinitely and NOTHING happens!)

    So my question is to you smart gents is how would you do this using the new Input System if it's at all possible?