Make a switch with a boolean or a var doesn't work

Hi,

I’m trying to find a way to switch a variable or a boolean each time you press a key,
I found this two ways on the internet:

if(Input.GetKeyDown(KeyCode.Space)){
variable = (variable == 0) ? 5 : 0;
}

or this one:

if(Input.GetKeyDown(KeyCode.A)){
test = !test;
}

But unfortunately it doesn’t work. The var/bool change once the key get pressed but then, they don’t change anymore.
Have anyone have the same issue ?
Im using Unity 4.1.5

Thanks in advance !

This i basic programming. Google a unity tutorial or a c# tutorial and you shall have your answer.

Thx i did’nt thought about google it lol

I fear that’s not a Unity problem. You need to show the whole script, such that we can exclude unwanted side effects from that script. What we won’t be able to see is, whether you deactivate the script somehow from another place.

When you post code, please use code tags.
http://forum.unity3d.com/threads/143875-Using-code-tags-properly

Those are both logically correct and will work. Did you put them in the update function? Did you make the variable public so you can see it in the editor when the key is pressed and the game is running? Otherwise add a print statement that shows the variable value. It does work.

no but seriously.

both code snippets you have written are correct code. They are written with the correct syntax, so we can’t help you if you don’t post more about everthing around it. As you posted, you where trying to find a snippet, well then google and shall find. But if you are implementing the snippet wrong well then we have no idea.

How is the rest of the code?
What is it placed on?
have you debugged your code with Debug.Log(variable); to see what actually happens in your code?

i did a quick google search here is a “pause” tutorial. Does pretty much what you are asking for, switches a boolean when pressing the space bar.

http://youtu.be/5sKKPg4kYzE

Hi guys, so now it’s work and I don’t know why because i didn’t change anything.
Like my code wasn’t working i made a new project and i writed a script only with the code shown on my first post.
I don’t know what happen but now it’s okay, thanks for the help