Why is this not working?

I have a simple piece of code to decrease an object’s “life” when I press the x button. When I play the game and press x, the life goes down random amounts and does so until it is deleted. Please can you help me find a solution to this or even tell me why this is happening and what I have done wrong.

Thank you in advance

This is the code which I am using:

public int life = 10;

void Start () {

}

void Update () {
	if (life < 1) 
	{
		Debug.Log ("You Win");
		Destroy (gameObject, 1f);
	}

	if (Input.GetKey ("x"))
	{
		life = life - 1;
	}
}

}

The GetKey method will return true every frame while the button is pressed. So if your game is running at 60 fps you will deduct from life 60 times per second.

If you want to treat a keypress as a single press then you need to use GetKeyDown.

This will return true during the first frame that the key is pressed. Then it won’t return true again until the key has been released and pressed again.