GetKey and GetKeyDown are always registered? [Answered]

I’m very much new to programming and to unity and I was able to follow a simple tutorial to make a ball game, (I’m certain most of you know the one) however when I went off to try and make a 2d plat former of my own the Player Character is always moving and I have no idea how to fix the issue.

function Update () {
	Movement();
}

function Movement () {
	if(Input.GetKeyDown(KeyCode.RightArrow));
	{
		//transform.Translate(Vector2.right * 4f * Time.deltaTime);
		Debug.Log ("Rightio");
	}
	if(Input.GetKeyDown(KeyCode.LeftArrow));
	{
		//transform.Translate(-Vector2.right *4f * Time.deltaTime);
		Debug.Log ("Leftadoodle");
	}
}

I used the Debug.Log s to see what was going on. This is to say, when I run the game preview I get an endless stream of “Rightio” and Leftadoodle."

You see the semicolon at the end of these lines?

if(Input.GetKeyDown(KeyCode.RightArrow));

if(Input.GetKeyDown(KeyCode.LeftArrow));

Get rid of those semicolons. In general, don’t ever put a semicolon between an if and the block of code it’s controlling.

This StackOverflow post will explain why, if you’re curious. The post is for Java, but it turns out that this quirk of syntax is a problem in many programming languages. :slight_smile:

Here is the good code:

function Update () {

Movement();

}

function Movement () {

if (Input.GetKey(KeyCode.RightArrow))
{
    rigidbody.AddForce(Vector3.right * 200 * Time.deltaTime);
}

if (Input.GetKey(KeyCode.LeftArrow))
{
    rigidbody.AddForce(Vector3.left * 200 * Time.deltaTime);
}

}

message me if it doens’t work.