- Home /
OnGUI: += and -= operations problem
So I'm having an issue that I didn't have in the previous version of Unity3d. I have a variable that I am using the += and +- operation on every time the user presses down on a specific key. All I want to do is add the value 1 but every time the key is pressed the variable gets the value 2 added/subtracted to it. I have debugged for Input.GetKeyUp() and Input.GetKeyDown() and both times the debug shows 2 outputs in the console. I'm not too sure what's going on. I have gone around the problem by just using a float and halfing everything but its a pain in the you know what. If anyone has a solution please help!
Thanks, Austin
That will have happened in 2.6 as well, my guess is you were just lucky with the number of events matching up each time
Answer by PeterDC · Oct 09, 2010 at 12:56 AM
The OnGUI()
function is called more than once per frame (at a minimum of twice), so if GetKeyUp()
and GetKeyDown()
are inside OnGUI()
, this would cause the problem you are experiencing. Putting GetKeyUp()
and GetKeyDown()
inside Update()
should fix your problem.
Answer by Bampf · Oct 09, 2010 at 01:34 AM
Perhaps the script is accidentally on more than one object?
Sometimes it's not obvious what object(s) a script is on. An easy way to find them is to put a line of code in the script:
Debug.Log("My name is: " + gameObject.name);
You could put this next to the increment/decrement code to see who is calling it.