Unity 4.6 UI - change image's source image via script

Hi,

I have buttons for levels, that have an image component. I set the image using the editor to the default “level unlocked” image. Now in the script, I am looping through all the levels, and for each, I read a playerprefs string associated with that level to determine if it was unlocked. If the level was not unlocked, I want to change the source image of that component to a “level locked” image.

I tried to set the image name to my new image’s name (clearly that failed atrociously)

gameObject.transform.GetChild(j).GetComponent<Image>().sprite.name = "my_new_image";

I tried having for each level two buttons, one representing ‘locked’ and one representing ‘unlocked’, disabling one and enabling the other. That worked, but I really am not liking the style to do it, and would prefer a solution that would fix the first approach.

Thanks a lot

What’s wrong?

You need to be changing the actual Sprite Object, rather the the Sprite Object’s name.
The Sprite is the actual “Image” of the Image UI Component in Unity 4.6.

How do I fix it?

While I can’t exactly talk you through it word for word, I can give you my example with comments.

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;
        }
	}
}

You can also change the sprite w/o changing the whole object like:

using UnityEngine;

using System.Collections;

using UnityEngine.UI;

public class YourScript: MonoBehaviour {

public Sprite red;

public Sprite green;

public Sprite blue;

void Start () {

	x = Random.Range (0, 2);
	if (x == 0)
		gameObject.GetComponent<Image> ().sprite = red;
	if (x == 1)
		gameObject.GetComponent<Image> ().sprite = green;
	if (x == 2)
		gameObject.GetComponent<Image> ().sprite = blue;
}

}

Hey, so if gameObject.GetComponent<Image> ().sprite = blue;isn’t working for you, try gameObject.GetComponent<SpriteRenderer> ().sprite = blue;

It worked for me, hopefully this helps someone else. :slight_smile:

For anyone still looking for this answer:

m_Image = GetComponent<Image>();
m_Image.sprite = myNewSprite;

https://docs.unity3d.com/ScriptReference/UI.Image-sprite.html