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
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;
}
}
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.
ddogle
June 11, 2017, 2:42am
6
Capn_Andy:
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.
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;
}
}