Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# and Unity3D while key is being pressed

Tags:

c#

unity3d

I am very new to C#. I am creating something in Unity to help me learn C# and Unity better.

I want to know why:

Input.GetKeyDown(KeyCode.UpArrow))

Only fires once when placed within:

void Update()

Since update is a loop, why is it not fired while I hold the key down (in my case causing a sphere to move)?

I have managed to get it working by using two bools that are altered when the key is pressed and released.

Here is my full script that I am playing with to move a sphere and simulate acceleration/deceleration:

using UnityEngine;
using System.Collections;

public class sphereDriver : MonoBehaviour {
int x ;
bool upPressed = false ;
bool downPressed = false ;
void Start()
{
    x = 0 ;
}

void Update ()
{
    if(x > 0) {
        x -= 1 ;
    }
    if(x < 0) {
        x += 1 ;
    }
    if(Input.GetKeyDown(KeyCode.UpArrow))
    {
        upPressed = true ;
    }
    else if(Input.GetKeyUp(KeyCode.UpArrow))
    {
        upPressed = false ;
    }

    if(upPressed == true)
    {
        x += 5  ;
    }

    if(Input.GetKeyDown(KeyCode.DownArrow))
    {
        downPressed = true ;
    }
    else if(Input.GetKeyUp(KeyCode.DownArrow))
    {
        downPressed = false ;
    }

    if(downPressed == true)
    {
        x -= 5  ;
    }

    transform.Translate(x * Time.deltaTime/10, 0, 0) ;
}

}
like image 427
imperium2335 Avatar asked Jul 06 '12 19:07

imperium2335


Video Answer


2 Answers

From the documentation on Input.GetKeyDown.

You need to call this function from the Update function, since the state gets reset each frame. It will not return true until the user has released the key and pressed it again.

This method is most useful for opening menus or other one time events. Such as continuing dialog.

You can use the methods as mentioned above, however you can use Input.GetKey to achieve your goal.

Returns true while the user holds down the key identified by name.

like image 88
Flickayy Avatar answered Oct 13 '22 12:10

Flickayy


The documentation says that this is the normal, expected behavior.

You probably want to use GetButton or GetAxis instead, since those indicate "pressed" as long as the key is held down (GetButton returns true, GetAxis returns 1).

like image 38
redtuna Avatar answered Oct 13 '22 12:10

redtuna