How do you change pressed sprite (C#)
On a unity UI Button there is an option called "Pressed Sprite" and this is the sprite which is displayed when you are clicking on the button. I'd like to be able to change the "Pressed Sprite" sprite in code.
Here's an example of what I've tried
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
void Awake ()
{
button = this.gameObject.GetComponent<Button>();
}
public void SetSprite()
{
if (enabled) {
button.spriteState.pressedSprite = redSprite;
} else {
button.spriteState.pressedSprite = greenSprite;
}
I also tried setting up a temp variable such as button = tempButton; and that was the same
I tend to get the following errors:
error CS0029: Cannot implicitly convert type `UnityEngine.Sprite' to `UnityEngine.UI.SpriteState'
error CS1612: Cannot modify a value type return value of `UnityEngine.UI.Selectable.spriteState'. Consider storing the value in a temporary variable
Answer by TBruce · Jun 07, 2016 at 06:30 PM
Coding is not necessary. Do this
Change the button Transition to Sprite Swap
Set the Pressed Sprite to the desired sprite
You can also set Highlighted Sprite and Disabled Sprite
Your good to go
Is this what you are trying to achieve?
Above works however I need the Pressed Sprite to actually change to a different Pressed Sprite during run-time.
What do you mean a different Pressed Sprite? The Sprite Image and the Pressed Sprite must be different for this to work so when you press the button the Sprite Image is swapped out with the Pressed Sprite and the button will show the Pressed Sprite as long as the button is held down. Then when the button is released the original Sprite Image is swapped back in.
I'd like to be able to swap the sprite during run-time. Just like you might want to change the "Source Image" sprite on the "Image" component
PERFECT! I've seen this question a few times but with no actual answers.
I think I kept tripping over the syntax for this but the below part has allowed me to get it working
SpriteState spriteState = new SpriteState();
spriteState = button.spriteState;
if (enabled)
{
spriteState.pressedSprite = redSprite;
}
else
{
spriteState.pressedSprite = greenSprite;
}
button.spriteState = spriteState;
Thank you. I am glad I could help. I hope that your project is a success.
Your answer
Follow this Question
Related Questions
How to change a button image with script? 1 Answer
UI button class 1 Answer
Smooth UI sprite animation. 1 Answer
CrossPlatformInput Detect Multiple Input Headache 1 Answer
UI Button OnClick() Will not Trigger Function Call 0 Answers