- Home /
Toggle Button: different color for ON and OFF state?
Hey guys, trying on this for hours now. Can you tell me if there is an build in way to set a ToggleButton's color depending on it's state (on/off)? More in detail: I have a toggle group, where only one toggle can be in the on state at the time. This should be visualized by the toggle color. All off toggles white, the on toggle gray. Seems to me like the most normal thing, but I don't get it working. Thanks, Tobi
Answer by Hellium · May 05, 2017 at 09:30 AM
I haven't tested the following code, but you will get the idea
private UnityEngine.UI.Toggle toggle ;
void Start()
{
toggle = GetComponent<UnityEngine.UI.Toggle>();
toggle.onValueChanged.addListener( OnToggleValueChanged ) ;
}
private void OnToggleValueChanged( bool isOn )
{
toggle.color = isOn ? new Color(0.5f, 0.5f, 0.5f ) : new Color(1, 1, 1 ) ;
}
https://docs.unity3d.com/ScriptReference/UI.Toggle-onValueChanged.html
Thank you very much! I don't really understand why it's not possible to select this color just like the normal and highlighted in the inspector, but your code works just fine.
I ended up doing this: For changing the toggle.color this workaround via Colorblock was necessary.
private Toggle toggle;
private void Start()
{
toggle = GetComponent<Toggle>();
toggle.onValueChanged.AddListener(OnToggleValueChanged);
}
private void OnToggleValueChanged(bool isOn)
{
ColorBlock cb = toggle.colors;
if (isOn)
{
cb.normalColor = Color.gray;
cb.highlightedColor = Color.gray;
}
else
{
cb.normalColor = Color.white;
cb.highlightedColor = Color.white;
}
toggle.colors = cb;
}
Hi I used your code for my toggle it was helpful, I couldn't figure out why I couldn't just tell it what color to be !
Answer by StephenA · Mar 05, 2020 at 10:51 PM
I've find another simplier workaround without code.
In your Toggle's Children select CheckMark and delete the source Image, then set the color to what you want and finally in the Rect transform Stretch to fill the background.
And that's all.
Verify that in your Toggle component Graphic (under Is On) still point to your modified CheckBox
Answer by unity_Fi7ZwG8y2_j8oQ · Dec 15, 2021 at 11:27 AM
OMG, I have wasted more time coding around this until I came across your answer. So much easier and works exactly how I thought Toggles should have in the first place!