[C#] Simple iteration seems to stack

Hello, unity gurus!
I have tried to add to my code another simple condition. When var value will be more than 10 (for example) something else will happen.
Please check the code, and tell me what am I doing wrong?

void Update ()
	{
		Renderer rend = GetComponent<Renderer>();
		Color nowColor = new Color(Random.value, Random.value, Random.value, 1.0f);
		int keyCounter = 0;

		if (Input.GetKeyDown (KeyCode.O)) {
			Debug.Log ("Nacisnal kurwa nacisnal");
			rend.material.color = nowColor;
			keyCounter++;
			Debug.Log(keyCounter); 
		} 
}

And the problem is :
Console always says the value of keyCounter is 1 even when I pressed key more than once. I think iteration might be a problem. Anyway, I could not find an answer for this problem. I understand it can be very silly reason that causing this “bug” but I would like to ask you for help otherwise I won’t go to my bed tonight.

Because you declare it within the Update function, the variable only exists within the function, and a new variable is created each time the function runs.

You initialise it to zero and then (sometimes) increment it. So its value can only ever be 0 or 1.

You need the variable’s “scope” to be bigger than that; it needs to exist outside the function in order for it to retain its value from one Update to the next.

So, the solution is to make it a field (or “member variable”) of the class, by moving its declaration outside of the function (but still within the class) like this…

int keyCounter = 0;
void Update ()
{
         Renderer rend = GetComponent<Renderer>();
         Color nowColor = new Color(Random.value, Random.value, Random.value, 1.0f);
 
         if (Input.GetKeyDown (KeyCode.O)) {
             Debug.Log ("Nacisnal kurwa nacisnal");
             rend.material.color = nowColor;
             keyCounter++;
             Debug.Log(keyCounter); 
         } 
 }

Doing this also makes the variable available to other functions in the class.

You declared your keyCounter variable inside your method. So keyCounter is a local variable. Each time Update is called you will use a new variable which you initialized with 0.

You have to declare a member variable in your class.

Thanks, Bonfire-Boy ! That do the work. I had a bad idea of declaration variables. I tried to do in the way you told but I don’t know why I was thinking that scope [public/private] need to be declared when is outside the function so I always got an error. Now I learned the public or private is for using this variable in different scripts or inspector access. Thank you once again!