Odd UI Code Issue

This is something I have done a hundred times before and just can’t work out what I have done wrong this time, I have been over my code several times, run the Profiler and all sorts of other diagnostic things.

The code below is called by a UI button, which uses the GameObject argument “socialBar” to enable/disable an additional UI component.

I have used a boolean to create a rudimentary “toggle” system, something I have also done a lot of, but for some reason it isn’t running any of the code, and I am receiving no errors.

using UnityEngine;
using UnityEngine.UI;

public class SocialShare : MonoBehaviour {

    bool socialOpen = false;
    public Image socialToggle;
    public Sprite socialIconClosed;
    public Sprite socialIconOpen;

    public void toggleBar(GameObject socialBar)
    {
        if(!socialOpen)
        {
            socialBar.SetActive(true);
            socialToggle.sprite = socialIconOpen;
            socialOpen = true;
        }
        if(socialOpen)
        {
            socialBar.SetActive(false);
            socialToggle.sprite = socialIconClosed;
            socialOpen = false;
        }
    }
}

How are you calling toggleBar? And do you have an EventSystem object?

I created the UI in the standard manner, so the EventSystem is all in place.
I am calling toggleBar using the built-in OnClick function at the bottom of the Button script, on my button object.

There’s no “else”, so you’re setting it to true and then setting it back to false in quick sequence. There were also far too many lines for something like this, so I shortened it. =)

public void toggleBar(GameObject socialBar)
{
    if(socialOpen)
        socialToggle.sprite = socialIconClosed;
    else
        socialToggle.sprite = socialIconOpen;

    socialOpen = !socialOpen;
    socialBar.SetActive(socialOpen);
}
1 Like