- Home /
Problem with On/Off Switch
Hey, I am implementing an on/off switch using the code below. The problem is that the switch gets off but it doesnt get on i.e. it goes inside the inner 'if' but it doesnt go inside the 'else'. Any ideas?
if (GUI.Button(new Rect(145, 50, 36, 30), "")) //Music
{
if(isOn_M)
{
music = music_off;
isOn_M = false;
}
else
{
music = music_on;
isOn_M = true;
}
}
You seem to have an awful lot of code for what looks like a simple boolean toggle. Can you not just use:
if (GUI.Button(new Rect(145, 50, 36, 30), "")) //$$anonymous$$usic
{
music = !music;
}
?
music is just a texture that changes the image of button I am using isOn_$$anonymous$$ as the bool
Answer by jokim · Aug 22, 2014 at 04:37 PM
What about :
if (GUI.Button(new Rect(145, 50, 36, 30), "")) //Music
{
isOn_M = !isOn_M;
if(isOn_M)
music = music_off;
else
music = music_on;
}
?
This might sounds obvious, but did you instantiate the boolean beforehand ?
Or even, are you changing it in between the clicks ? is it accessed anywhere else ?
EDIT
Ok, You need to initialise the boolean outside the function.
put this line :
bool isOn_M = false;
inside the class, but outside of functions
(btw, i'm assuming this is c#, i might be wrong)
The reason being that a variable declared inside a function only exists within that function. once the function is done executing, the variable is "disposed of", to free memory. You need the variable to be part of your class. so that it "lives" as long as your class exists.
I hope i'm being clear.
I initialized it just above the outer if statement. And no it isnt being accessed anywhere else. I tried your code. It doesnt work. Dont know why :(
There, Edited my answer.
If you were instantiating the boolean INSIDE the function, the value is only valid while the function is being executed, once it exits, the value is lost. (and will be instantiated again when it goes back in)