Unity 4.6 Change Highlighted Button Sprite using C#

Hi there,

I am currently using the SpriteSwap transition mode for a button in the Unity 4.6 beta, and was wondering if there is there a way to permanently change the highlighted sprite from the original assigned in the Inspector through code when that button is pressed?

I’m so happy, I’ve found an answer that worked for me here:

Sprite newSprite = Resources.Load<Sprite>("sprites/somesprite");
SpriteState st = new SpriteState();
st.disabledSprite = newSprite;
st.highlightedSprite = newSprite;
st.pressedSprite = newSprite;
_button.spriteState = st; 

I think that means that you cannot access the variables in the existing SpriteState, but you can just create a new SpiteState that overrides the old one :smiley:

It looks a little tricky at the moment, Its very fresh meat and needs to get a good cooking. But I think its the image variable in the selected stuff.

I have not been able to test it as I have not been able to access the UI namespace yet

But I think this answer might get you a little closer to a solution Unity 4.6 GUI select button via script - Unity Answers

a little convoluted right now and I am sure it will change.

Here is something I found on another post:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;

 public class TestMenu : MonoBehaviour 
 {
     /// <summary>
     /// This is the Sprite we're going to swap to.
     /// </summary>
     /// <remarks>
     /// This is set in Unity's Inspector.
     /// </remarks>
     public Sprite OtherSprite;
 
     /// <summary>
     /// The Array of Images.
     /// </summary>
     Image[] images;
 
     // Use this for initialization
     void Start() 
     {
         // Get all components of type Image that are children of this GameObject.
         images = gameObject.GetComponentsInChildren<Image>();
 
         // Loop through each image and set it's Sprite to the other Sprite.
         foreach (Image image in images)
         {
             image.sprite = OtherSprite;
         }
     }
 }