How to access SourceImage component of a button in new GUI 4.6

hello community,

in the new GUI a button has an Image script attached to it by default. Source Image is the field you put the image that the button will have.
What i want is to be able to change that image in code c# at runtime after a condition is met.

Can you help me ?

thanks for your time

First of all, you need “using UnityEngine.UI” to be able to access Buton and/or Image components from your script. After that, all you need is a reference to the Image your button is using and then change the sprite or overrideSprite property’s of that Image to your new Sprite

using UnityEngine;
using UnityEngine.UI;

[RequireComponent(typeof(Button))]
public class example : MonoBehaviour
{
    public Sprite newsprite;
    public bool condition;

    private Button button;

	void Start ()
    {
        button = GetComponent<Button>();
	}

	void Update ()
    {

        if (condition)
        {
            // If you want to change the sprite for only a short time,
            // and use a default whenever your condition is false
            button.image.overrideSprite = newsprite;

            // But if you really want the source image,
            // use the following line instead
            // button.image.sprite = newsprite;
        }
        else
        {
            // Setting the overrideSprite back to null will cause
            // the image to display the original value of image.sprite again
            button.image.overrideSprite = null;
        }
	}
}

You can do this without variables.

GameObject.Find("carscore1").GetComponent<Button>().image.overrideSprite = null;

Now you can change the sprite in those buttons seperately. Just change the game objects name.