0
\$\begingroup\$

I'm trying to make the sprite of my button change on click, and i used this script to achieve it:

public Button botonPlayMaster; //i assign the button on the inspector
Image imagenBoton; 
public Sprite botonPlay; // same with the sprites, i send them on the inspector
public Sprite botonStop; 
    
    
    // Start is called before the first frame update
    void Start()
    {
        imagenBoton = botonPlayMaster.GetComponent<Image>(); // i get the component from the button
    
    }


public void cambiaSprite (){
        if (imagenBoton.sprite == botonPlay) {
            imagenBoton.sprite = botonStop;
        }
        else 
            {
                imagenBoton.sprite = botonPlay;
            }
    }

This script is attached to a GameManager GameObject. I assign the sprites and the GameObject Button on the inspector, and then send the GameManager object to the OnClick() function on the button's inspector and select the cambiaSprite() function. But when i click, nothing happens. Any help would be appreciated. Thanks!

\$\endgroup\$
  • \$\begingroup\$ Let me know if my answer was something you were looking for, and if it solved your issue. \$\endgroup\$ – ezez Nov 17 at 12:55
0
\$\begingroup\$

So you are basically trying to create a button that toggles between sprite A and sprite B?

Note: Unity UGUI Button has different transition modes; Color Tint (default), Sprite Swap and Animation. If you use Sprite Swap mode, example below might not work like expected. So set your Button Transition mode to None (otherwise you may not see your replaced Button default Sprite).

So you could do something like this:

// assign these from Inspector
[SerializeField] Button button;
[SerializeField] Sprite spriteA;
[SerializeField] Sprite spriteB;

private void OnEnable() =>
    button.onClick.AddListener(ChangeSprite);

private void OnDisable() =>
    button.onClick.RemoveListener(ChangeSprite);

void ChangeSprite()
{
    button.image.sprite = button.image.sprite == spriteA ? spriteB : spriteA;
}

Note: if you (for some reason) wanted to change Button mode specific sprites instead of changing the default sprite, you'll have to get the button spriteState and change its sprites (Highlighted, Pressed...).

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Thanks you for answering! It fixed itself, i think. I'm not sure what happened really, i just ctrl+z a bit because of another issue i had and then it worked. \$\endgroup\$ – Morganuz Nov 17 at 21:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.