- Home /
How can I fill an image array with a script
Im trying to automatically fill an image array that represents health.
The line "Hearts = GameObject.findGameObjectswithtag("Hearts")" gives me an error saying it can't convert an image array to a gameobject array. What is the UI equivalent of this?
Answer by finnjwohner · Jul 13, 2020 at 12:19 AM
GameObject.FindGameObjectsWithTag() returns an array of GameObjects, so you could store that array and then loop through each gameobject, getting it's Image component to get your array of images, it'll look something like this:
Using UnityEngine.UI;
private Image[] GetHearts() {
// Get the heart objects
GameObject[] heartObjects = GameObject.FindGameObjectsWithTag("Hearts");
// Declare an array of hearts with the amount of hearts present
Image[] hearts = new Image[heartObjects.Length];
// Loop through the hearts, adding each image component to the array
for (int i = 0; i < hearts.Length; i++) {
hearts[i] = heartObjects.GetComponent<Image>();
}
// Return the hearts array
return hearts;
}
Image[] hearts = GetHearts();
You'll probably need to change a few things to make it work with your code but the general idea should fit. Hope I could help :)
Ah thanks, I was forgetting that Image refers to the component and not the actual object
Your answer
Follow this Question
Related Questions
Transform translate not working properly in Canvas 0 Answers
Unity UI not showing some Images 0 Answers
Image Displaying Bleached Texture. 0 Answers
Create UI Mask from Childrens images 2 Answers
Change UI GUI Image Sprite at runtime .. Unity 5 .. js 1 Answer