Search Unity

how to use input While holding a key

Discussion in 'Scripting' started by kaydenfinley, Aug 3, 2019.

  1. kaydenfinley

    kaydenfinley

    Joined:
    Mar 12, 2019
    Posts:
    3
    so i have this rotate script but instead of rotating while holding a key, it rotates 3 units to the left or right when i press a key:

    Code (CSharp):
    1.  void Update()
    2.     {
    3.         if (Input.GetKeyDown(KeyCode.A))
    4.         {
    5.             transform.Rotate(new Vector3(0f, 0f, 2f));
    6.         }
    7.  
    8.         if (Input.GetKeyDown(KeyCode.D))
    9.         {
    10.             transform.Rotate(new Vector3(0f, 0f, -2f));
    11.         }
    12.  
    13.     }
     
  2. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    14,400
    GetKeyDown (and GetKeyUp for that matter) has an internal limiter that prevents it from registering again until the key has been released. To keep registering the key you need to use GetKey.

    https://docs.unity3d.com/ScriptReference/Input.GetKey.html

    Code (csharp):
    1. void Update()
    2. {
    3.         if (Input.GetKey(KeyCode.A))
    4.         {
    5.             transform.Rotate(new Vector3(0f, 0f, 2f));
    6.         }
    7.  
    8.         if (Input.GetKey(KeyCode.D))
    9.         {
    10.             transform.Rotate(new Vector3(0f, 0f, -2f));
    11.         }
    12. }
     
  3. kaydenfinley

    kaydenfinley

    Joined:
    Mar 12, 2019
    Posts:
    3
    Thanks this worked!