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
asked May 19 '26 16:05
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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With