Weird highlight behavior after updating sprite of pushbutton

I’m trying to make a sprite swap “pushbutton” that that alternates between pushed state after the first click, then back to normal state after the second click, and so on. In addition, it should support a highlighted sprite during mouse over.

I initially setup a Sprite Swap button with “Pressed Sprite”, “Highlighted Sprite”, and “Target Graphic” (from Image component’s “Source Image”) that worked great before adding support for the “pushbutton” behavior. But after adding the OnClick code to toggle the GameObject.Image.sprite value, the pushbutton behavior works great, but the highlighted sprite exhibits weird behavior.

Now, after pushing the button, the pushed sprite is drawn correctly, but hovering over the button no longer highlights – until l click anywhere outside the button. Then the highlighting works again.

The partially working OnClick behavior is:

public void OnClick() {
    if (_pressed) {
        myButton.GetComponent<Image>().sprite = Resources.Load<Sprite>("normal");
    } else {
        myButton.GetComponent<Image>().sprite = Resources.Load<Sprite>("pressed");
    }
    _pressed = !_pressed
}

Any way to fix this?

1 Answer

1

If you want to change the sprites used by a Sprite Swap button, you need to change the spriteState parameter of the Button.

SpriteState temp = new SpriteState();
temp.pressedSprite = your_Pressed_Sprite_reference;
temp.highlightedSprite = your_Highlighted_Sprite_reference;
temp.selectedSprite = your_Selected_Sprite_reference;
myButton.spriteState = temp;

When I did used this in the past, I still changed the Button’s Image sprite to the selected sprite, but I don’t know if this is necessary.