unity while key pressed code example

Example 1: how to see if they are aholding down a key unity

input.GetKey("Key")

Example 2: how to check if key is held in unity

float startTime; // declare this outside any function
 
   void Update () {
     if (Input.Get$$anonymous$$eyDown("w")||Input.Get$$anonymous$$eyDown("s")){
       // key pressed: save the current time
       startTime = Time.time;
     }
     if (Input.Get$$anonymous$$eyUp("w")||Input.Get$$anonymous$$eyDown("s")){
       // key released: measure the time
       float timePressed = Time.time - startTime;
       // do here whatever you want with timePressed
     }
     RandNum = Random.Range(1, 1000);
     if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.W) || Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.S)){
       if(RandNum > 1){    
         if(RandNum < 1000){
           inBattle ();
         }
       }
     }
   }

Example 3: unity when key pressed

void Update()
    {
        if (Input.GetKeyDown("space"))
        {
            print("space key was pressed");
        }
    }

Example 4: unity key pressed

using UnityEngine;

public class Egsample_script : MonoBehaviour
{
    [SerializeField] KeyCode your_key;
    //select a key under inspektor
    void Update()
    {
        if (Input.GetKey(your_key))
        {
            print("your selekted key was pressed");
        }
    }
}

Tags:

Misc Example