Search Unity

Question How to make Input work consistently across frames?

Discussion in 'Scripting' started by OGKoji, Aug 14, 2022.

  1. OGKoji

    OGKoji

    Joined:
    Apr 17, 2022
    Posts:
    1
    I've noticed a problem when using Inputs under Update, in which sometimes it will not consistently execute. I presume this is due to something with it being dependent on the frames? I have an example where a rocketBoost particles wouldn't consistently immediately play pressing space, and would only guarantee to play if I held space. Letting go of space, is supposed to stop rocketBoost particles. Example:

    Code (CSharp):
    1. if (Input.GetKey(KeyCode.Space)) { rocketBoost.Play(); } else { rocketBoost.Stop() }
    The Input is inconsistent and wouldn't immediately play the rocketBoost particles upon pressing space. To fix this, I had to wrap it in an if statement first checking that it is not playing.

    Code (CSharp):
    1.  if (Input.GetKey(KeyCode.Space)) { if(!rocketBoost.isPlaying) { rocketBoost.Play(); } }
    I wanted to know if there is a proper way to go about fixing Inputs not working consistently under frames, or if my presumption is even correct that this is due to the frames fault. Thank you.
     
  2. RadRedPanda

    RadRedPanda

    Joined:
    May 9, 2018
    Posts:
    1,647
    GetKey returns true every frame it's pressed down. If you just want it to do it once the key is pressed, you should use GetKeyDown.
     
    OGKoji likes this.