UnityRef is currently in early development. Some features may be incomplete and/or not functioning.

UNITYREF

Your Pit Stop For Solving ANYTHING in Unity

architecture

[Key Press] Stop Input.GetKeyDown Double Triggers

Solution

Unity 2021.x - Unity 6.3.x

Published Sun, Mar 22

Issue

 An input-driven action is being triggered continuously while a key is held down. This behavior leads to unintended physics accumulation or repeated logic execution instead of a single, controlled trigger event using Input.GetKeyDown.

Quick-Fix

Ensure atomic action execution by transitioning from continuous polling to frame-specific edge detection using Input.GetKeyDown.

Expand Analysis

To restrict an action to a single execution per key press, the logic must differentiate between continuous polling and edge-triggered detection. Input.GetKey returns true for every frame the key is held, whereas Input.GetKeyDown returns true only for the frame in which the key is first depressed.

  1. Locate the input detection logic in your script.
  2. Replace instances of Input.GetKey with Input.GetKeyDown to isolate the trigger to a single frame.
  3. Ensure the logic is processed within Update rather than FixedUpdate to avoid missing the specific frame of the input.
  4. When interacting with a Rigidbody, apply the force using ForceMode.Impulse to ensure the momentum change is instantaneous and not dependent on the duration of the key press.

Additional Tips

  • Consider utilizing the new Input System Package for more complex requirements, as it provides built-in interaction types like ‘Tap’ and ‘SlowTap’.
  • For actions requiring a specific time delay between presses regardless of key release, implement a float-based cooldown timer in your script.

Copy


using UnityEngine;

public class PlayerController : MonoBehaviour
{
    public float upwardForce = 10.0f;
    public Rigidbody targetRigidbody;

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            targetRigidbody.AddForce(Vector3.up * upwardForce, ForceMode.Impulse);
        }
    }
}

Related Posts Haven't quite found a solution to your problem? We think these posts might help you.

Content inspired by a Unity discussion post.