UI Button - Sprite Swap via Code

Hey guys,

I am currently experimenting with the new UI System in Unity 4.6 Beta, I have implemented a button in my game which function as a sound on/off button. What I want to do next is to change the sprite based on the sound settings e.g. so when sound is enabled, a speaker icon will be shown and when the sound is disabled, a mute icon will be displayed. Does anyone have any idea how this could be achieved?


Hey there! I stumbled on your answer while trying to figure out something similar. What I ended up doing was creating an iconSet class and changing the button’s values to match the certain iconSet. So for your case you could have a soundEnabled iconSet and soundMuted set.

Then when the sound is muted just swap them out~ I have a scriptable object that just contains a generic List of iconSets.

The class:

class iconSet {
	var def : Sprite;
	var hover : Sprite;
	var press : Sprite;
	var disabled : Sprite;

So make a list : List.< iconSet> then populate it for sound on/muted.

As for switching between them you could do something like:

function changeSprite (swap : int){
	gameObject.GetComponent.<Image>().sprite = list[swap].def;
	gameObject.GetComponent.<Button>().spriteState.highlightedSprite = list[swap].hover;
	gameObject.GetComponent.<Button>().spriteState.pressedSprite = list[swap].press;
	gameObject.GetComponent.<Button>().spriteState.disabledSprite = list[swap].disabled;

Where swap = 0 for sound and swap = 1 for muted. I did mine in US but it shouldn’t be too hard to change it to C#

public Texture2D Texture1;
public Texutre2D Texture2;
public Texutre2D mainTexture;
public bool textureBool;

    void Awake() {

     void OnGUI() {
       if (GUI.Button (new Rect (50,500,50,50),  mainTexture)) {

             mainTexture = Texture2;   //Swap to Texture2
                mainTexture = Texture1;