Keypress Left is called twice in Update when key is pressed only once

Keypress Left is called twice in Update when key is pressed only once

I have a piece of code that is changing the position of player when left key is pressed. It is inside of Update() function. I know, Update is called multiple times, but since I have an ifstatement to check if left arrow is pressed, it should update only once. I have tested using print statement that once pressed, it gets called twice.
Problem: 
Position updated twice when key is pressed only once.
Below given is the structure of my code:
void Update()
{
    if (Input.GetKeyDown (KeyCode.LeftArrow)) 
    {
        print ("PRESSEEEEEEEEEEEEEEEEEEDDDDDDDDDDDDDD");
    }
}

How can I fix this?

Solutions/Answers:

Answer 1:

I can think of two ways of solving this

  1. Use LateUpdate function instead of Update

    LateUpdate is said to be called just once per frame, so it should fix the problem. However, depending on your project, its side effect could be to change your train of thought when dealing with logic for the same execution order of scripts.

  2. Use a flag

    You could use a flag for a double check.

Example code:

using UnityEngine;
using System.Collections;

public class YourClass : MonoBehaviour
{
    private bool isKeyPressed = false;

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.LeftArrow) && !isKeyPressed)
        {
            isKeyPressed = true;
            // TODO
            // your logic here when button pressed
        }

        if (Input.GetKeyUp(KeyCode.LeftArrow) && isKeyPressed)
        {
            isKeyPressed = false;
            // TODO
            // your logic here when button released
        }
    }
}

Answer 2:

Double check that this script isn’t in the scene multiple times, either attached to multiple objects or attached multiple times to the same object. That latter mistake trips me up once in a while.

Answer 3:

I had the same script on 4 buttons and it was getting called 4 times as expected from reading this thread. Here is how I solved it. Each button has a name. Instead of checking for bool like the answer above, check for the name button. a simple print function reveled the name of the button and I did this.

void Update(){
    if(Input.GetKeyDown(KeyCode.UpArrow) && gameObject.name == "down 1 force Button"){
        print("I was touched: " + gameObject.name);
    }
}

References