- Home /
How would I detect if key get pressed 2 times
Hi, I have a variable which grants the player access to place objects. Now, if I for example press B, it should grant access to the player to place objects, and if I press B again it should remove access, and so on so forth. What's the best way to do this?
Answer by vexe · Oct 20, 2013 at 11:21 AM
Just use a bool, and then toggle it.
bool grantAccess = false;
if (Input.GetKeyDown(KeyCode.B))
grantAccess = !grantAccess;
// somewhere else
if (grantAccess)
placeObjects();
Anytime :) - Also, as meat5000 suggested, make sure you know the differences of each of Input.GetXXX family members, see this.
Yeah I wasn't gonna spell it out. By the time I submitted, your answer had already been accepted :D So i deleted it :P
Interestingly, it still says 2 answers. One for the bug thread.
Well, just initialize it to true ins$$anonymous$$d:
bool grantAccess = true;
And you don't need the else-if
, just an else
, if the if condition was false, execution would automatically jump to the else
part:
if (grantAccess) {
CursorGrid2.meshActive = 1;
}
else {
CursorGrid2.meshActive = 0;
}
Better yet, use the ternary operator:
CursorGrid2.meshActive = grantAccess ? 1 : 0;
This mean: is grantAccess true? if so, set CursorGrid2.meshActive
to 1, else 0.
Yes. I should actually use booleans, but from my years of program$$anonymous$$g I've barely touched booleans, I've always used integers. So I will try to use booleans more, thanks! Now, what you helped me with was that I need to allow the user to place objects at certain points, for example when you press the build button (b). When you press it, it should allow you to build and when you press it again you should not be able to build. I solved this in the beginning by having if statements at every part of the code which controlled the placement functions, and to call it I had one button to allow and one to decline. I didn't see that as a good way to have it, because almost every game nowadays have that function, so I thought that it shouldn't be that hard to do. So you've helped me with that and I'm truly graceful, thank you!
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Seven key press 3 Answers
Multiple Cars not working 1 Answer
How do I get my door to work? 1 Answer
How do I play an animation with the 'E' key when I enter a trigger 2 Answers