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

Coding is not necessary. Do this

  1. Change the button Transition to Sprite Swap
  2. Set the Pressed Sprite to the desired sprite
  3. You can also set Highlighted Sprite and Disabled Sprite
  4. Your good to go

Is this what you are trying to achieve?

71679-inspector.png