Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to repeat function while button is held down (New unity input system)

Tags:

c#

unity3d

Trying to repeat the function function OnAttack() continuously while a button is being held down.

Basically I'm looking for an equivalent to Update() { GetKeyDown() {//code }} But with the input system.

Edit: using a joystick, cant tell what button is being pressed.

like image 706
Sabishī Avatar asked Jan 21 '20 08:01

Sabishī


People also ask

Can you use both input systems in Unity?

It's possible to have both the legacy input module and the new input system active at the same time by going to the project settings and setting the active input handling to Both. This is especially useful when converting an existing project to use the new input system.


2 Answers

Okay I solved it by using "press" in the interactions and giving that The trigger behavior "Press and release", then did

bool held = false;
Update()
{
    if(held)
    {
        //animation
    }
    else if(!held)
    {
        //idle animation
     }
}
OnAttack() {
    held = !held;
}

This way if I press the button held goes to true so it repeats the animation every frame, letting go makes "held" untrue and does the idle animation

like image 87
Sabishī Avatar answered Oct 06 '22 23:10

Sabishī


Essentially, the function you assign to the button will be triggered twice per button press, once when it is pressed (performed), and once when it is released (canceled). You can pass in this context at the beginning of your function, just make sure you are using the library seen at the top of this script. Now you can toggle a bool on and off stating whether or not the button is pressed, then perform actions during update dependent on the state of the bool

using static UnityEngine.InputSystem.InputAction;

bool held = false;
Update()
{
    if(held)
    {
        //Do hold action like shooting or whatever
    }
    else if(!held)
    {
        //do alternatice action. Not Else if required if no alternative action
     }
}
//switch the status of held based on whether the button is being pressed or released. OnAttack is called every time the button is pressed and every time it is released, the if statements are what determine which of those two is currently happening.
OnAttack(CallbackContext ctx) {
    if (ctx.performed)
            held= true;
    if (ctx.canceled)
            held= false;
} 
like image 5
Oliver Philbrick Avatar answered Oct 06 '22 22:10

Oliver Philbrick