Create a button with an active and inactive state? (Or toggle effect)

Hello. How would I create (using the new 4.6 UI beta tools), a button that had an inactive/active state? For example, I have a sub-menu that I want to open when I click on this button, but when I click on the button again, it closes it, such as a toggle.

What would be the best way to approach this? In the on click events for the button, I haven’t found a way to switch events around…

Hi TrivialRoo,
This is a similar post: Button OnClick as toggle - Unity Engine - Unity Discussions
Hope it helps!

Is there a way of toggling a sprite? Because I want it to change sprites when I click it, but it won’t toggle because it isn’t a Dynamic Bool.

You could try using: Sprite Renderer’s enabled property.

Correction: Sprite is Game Object so it has SetActive property!

Sorry. I meant changing the sprite to something else.

Is something like this you are trying to do: uGUI Graphical Toggle Button - Unity Engine - Unity Discussions ?
You can use this script for changing Sprites ( using default checkbox ):

using UnityEngine;
using UnityEngine.UI;

[RequireComponent(typeof(Toggle))]
public class ToggleSprites : MonoBehaviour
{
    public Sprite Inactive = null;

    private Toggle _Toggle = null;
    private Image _Background = null;
    private Sprite _BackgroundActive = null;

    void Awake()
    {
        _Toggle = GetComponent<Toggle>();
        _Background = transform.GetComponentInChildren<Image>();
        _BackgroundActive = _Background.sprite;
    }

    public void Toggle()
    {
        if (_Toggle.isOn)
            _Background.sprite = _BackgroundActive;
        else
            _Background.sprite = Inactive;
    }
}

Hope it helps!
I got it wrong: “Because I want it to change sprites when I click it”. English is not my first language, my bad!

1 Like

Thank you so much Caio_Lib!

Yes Caio_Lib!
I use similar idea:

using UnityEngine;
using UnityEngine.UI;

public class ToggleExtension : MonoBehaviour {
    public Image bkg;
    public void toggleChangedHandler()
    {
        if (GetComponent<Toggle>().isOn)
        {
            bkg.color = new Color(bkg.color.r, bkg.color.g, bkg.color.b, 0);
        }
        else
        {
            bkg.color = new Color(bkg.color.r, bkg.color.g, bkg.color.b, 255);
        }
    }
}

Hi,
Actually we don’t need to write the code to swap sprites of a toggle, look the image I attached.

2246591--150037--Unnamed QQ Screenshot20150812115927.png

1 Like