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;
...
}
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 () {
}
}
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.