Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity3D C# Button sprite swap - attach images at runtime

I am creating buttons when my "Hero Selection Menu" is being created. These buttons will get their related images/Sprites depending on the "Hero" they will represent.

I have the following method, but I don't understand which variable I have to apply the sprites to.

Button _thisButton;
Sprite  _normalSprite;
Sprite _highlightSprite;

protected override void DoStateTransition (SelectionState state, bool instant){
    switch (state) {
    case Selectable.SelectionState.Normal:
        _thisButton.image = _normalSprite;    //.image is not correct
        Debug.Log("statenormalasd");
        break;
    case Selectable.SelectionState.Highlighted:
        _thisButton.image = _normalSprite;    //.image is not correct
//...
    }

The states are definitely working, I have confirmed it through Debug.Log(...);

Again the problem is: which value has to be changed if not .image?

Thanks in advance, Csharpest

like image 492
Csharpest Avatar asked May 19 '26 16:05

Csharpest


2 Answers

You're trying to attach a sprite to a button component. The sprite is in the Image component. Check this out!

GameObject buttonGameObject;
Sprite newSprite;

void Start() {
    buttonGameObject.GetComponent<Image>().sprite = newSprite;   
}

But to fix your code, you'd probably do something like:

Button _thisButton;
Sprite  _normalSprite;
Sprite _highlightSprite;

protected override void DoStateTransition (SelectionState state, bool instant){
    switch (state) {
    case Selectable.SelectionState.Normal:
        _thisButton.GetComponent<Image>().sprite = _normalSprite;   
        Debug.Log("statenormalasd");
        break;
    case Selectable.SelectionState.Highlighted:
        _thisButton.GetComponent<Image>().sprite = _normalSprite;    
    }
like image 82
Fredrik Schön Avatar answered May 22 '26 04:05

Fredrik Schön


If you want to change a button spriteswap sprites in a script you must use spriteState, you can do something like this;

Button _thisButton;
Sprite  _normalSprite;
Sprite _highlightSprite;

void ChangeSprites(){
  // _thisButton.transition = Selectable.Transition.SpriteSwap;
  var ss = _thisButton.spriteState;
  _thisButton.image.sprite = _normalSprite;
  //ss.disabledSprite = _disabledSprite;
  ss.highlightedSprite = _highlightSprite;
  //ss.pressedSprite = _pressedSprie;
  _thisButton.spriteState = ss;
}

Unity makes the swap in the button automatically if you are using a normal button and selecting SpriteSwap, if you need to change the transition option then uncomment the first line of the function.

like image 36
Juan Bayona Beriso Avatar answered May 22 '26 06:05

Juan Bayona Beriso