Change UI-Button Source Image in Code

Hi, i need to change the Image in the UI-Button in Code, this is what i have:


How i change the Image of the Button in Code?

What i have in Code:

var objWithImage = GameObject.Find("11");
//Get Image Component? Or Button?
var image = objWithImage.GetComponent<Image>(); 
//Change image of object

Could someone help me with this problem?

1 Like

You’re pretty close; I’m not sure the JS but in C#:

Sprite newSprite = sprite; // ← This is the new sprite
Image theImage = GameObject.Find(ā€œ11ā€).GetComponent();
theImage.sprite = newSprite;

The ā€œImageā€ class has the ā€œ.spriteā€ property that contains the image data.

4 Likes

Thanks that helped!

1 Like

hi,
Im not sure what im doing wrong but when i use ur same code and im seeing this error: ā€œThe type or namespace name `Button’ could not be found. Are you missing a using directive or an assembly reference?ā€

this is my code

usingUnityEngine;
usingSystem.Collections;

public class Main : MonoBehaviour
{
bool mute = false;
//Button image;
//Image image;
//Button image = GameObject.Find(ā€œMusic onā€).GetComponent();
Image image = GameObject.Find(ā€œMusic onā€).GetComponent();
public Sprite myFirstImage;
public Sprite mySecondImage;
publicvoidmuteMusic()
{
if(!mute)
{
image.SourceImage = mySecondImage;
}
else
{
image.SourceImage = myFirstImage;
}
}

Mr.Gamer

You need to put " using UnityEngine.UI; " at the top of your script, in order to use the UI components, which in your case, the button component.

Hello,

i’m new i try add buti get error Assets/Scripts/Player.cs(133,45): error CS1525: Unexpected symbol `’

I try use your idea to pause game and change button pause

void Pause ()
{

if (canpause) {

Sprite newSprite = sprite;
Image theImage = GameObject.Find(ā€œP2ā€).GetComponent();
theImage.sprite = newSprite;

Time.timeScale = 0;
canpause = false;
}

else
{

Time.timeScale=1;
canpause = true;

}
}