- Home /
how to change source image of UI image in code (newest version of unity)
Im trying to change an image of an object that is child of UI. I searched for answers but all of them says to do this:
ImageName.sprite = newImage
It doesn't work for me, unity ignors this line and shows no error about it, the image stays with "none" sprite. how can I fix this?
here is some of my code:
private Image GetFace(Sprite player_f)
{
Image face = PlayerBarExample.GetComponentInChildren<Image>();
face.sprite = player_f;
...
}
Answer by AdiDidIt · Jul 06, 2018 at 10:01 AM
I found my problem. I used GetComponentInChildren(); and forgut that there are other images which are child of this objectץ here what I did:
Image[] images = PlayerBarExample.GetComponentsInChildren<Image>();
Image face = images[0];
foreach (Image image in images)
{
if (image.gameObject.CompareTag("face"))
face = image;
}
and now its works, thx for the help.
Answer by hameed-ullah-jan · Jul 05, 2018 at 05:38 PM
Hi, Try this code, i've checked it and it has no issue.
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI;
public class changeimage : MonoBehaviour {
public Sprite newImage;
private Image myIMGcomponent;
// Use this for initialization
void Start () {
myIMGcomponent = this.GetComponent<Image> ();
myIMGcomponent.sprite = newImage;
}
// Update is called once per frame
void Update () {
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612170111im_/https://answers.unity.com/themes/thub/images/avi.jpg)