- Home /
The question is answered, right answer was accepted
How To Get UI Button To Stay In A Pressed State
OK this is one of those things about the new UI system that just drives me outright nuts as to why there does not seem to be a built in way to do this. But what if I want a state of the button to stay pressed until clicked again? Is there some built in way to do this that I am missing or do you have to code this somehow?
Answer by DiegoSLTS · Mar 08, 2015 at 03:42 PM
There is a way to do that with Unity UI. What you're describing is a Toggle, not a Button.
Perfect!! Thanks DiegoSLTS, I have been trying to figure out how to get that effect fro a while, I'm hoping I can still get a sound to play when the toggle is set to on or off as in a tone for each click that is to say ;)
You can do this with a button as well. In the OnClick call a public function that just sets a bool to the opposite of itself.
public void ShiftClicked()
{
shiftOn = !shiftOn;
if (shiftOn)
ShiftImage.color = Color.gray;
else
ShiftImage.color = Color.white;
}
I use this in a keyboard script to set shift on/off.
I'm a little confused as to exactly HOW the toggle button actually turns something on or off depending on it's state??
What do you mean by turning something on and off? The toggle just have a state of pressed (it's "isOn" property), you turn something on and off using that value, but you have to code what it means to have a toggle checked or unchecked.
When you have to select the fuction that receives on bool parameter to be called for that event you'll find the function at the top in the "Dynamic bool" section, and the fuction at the bottom in the "Static paremeters" section. When you choose the dynamic option, the function receives the new value of the toggle (if you checked it, the parameter would be true). When you choose the static option the value the function receives is the one you set in the inspector.
I'm not sure I follow. I have a microphone script that I simply want to enable and disable with the same button. I think I am missing something simple on how toggles work but I'm not seeing it. A freaking tutorial on these blasted buttons would be nice somewhere but I have had no luck finding one.
Follow this Question
Related Questions
How do I highlight multiple buttons at once? 1 Answer
Toggles ToggleGroups highlighting problem. 1 Answer
Buttons on mobile activating OnHighlight Animation without touching them. 0 Answers
Highlight button via script at runtime 5 Answers
How to handle button highlighted state on Android with touch/mouse/controller? 0 Answers