Tomas
Tomas

Reputation: 129

How to reference to Image component in child element?

I have a prefab:

enter image description here

Both GridSpace and Image have image component. GridSpace's image component is to store button color and Image's image component is to store picture. Next, I'm adding several GridSpace prefabs to the scene but I want every Image element to have different, random image. I'm using this command to add prefab elements and link arrays elements with created objects' components:

  for (int y = 0; y < gridsInRow; y++)
        {
            for (int x = 0; x < gridsInColumn; x++)
            {
                GameObject newSmoke = Instantiate(gridSpacePrefab, new Vector3(0, 0, 0), Quaternion.Euler(0, 0, 0)) as GameObject;
                buttonTextArray[x, y] = newSmoke.GetComponentInChildren<Text>();
                imageArray[x, y] = newSmoke.GetComponentInChildren<Image>();
            }
        }

I wanted to have imageArray to store references to Image's image components but it seems that it's referencing to image component in GridSpaces' elements. Do you know what is wrong with the code above? Or how could I reference the image component in Image element? What's more, buttonTextArray stores references to Text component in Text element. The only problem is with this image component.

Upvotes: 0

Views: 468

Answers (1)

Daahrien
Daahrien

Reputation: 10320

GetComponentInChildren also looks inside the current object (not only its children) so it returns the image component of the GridSpace.

You can do it like this:

imageArray[x, y] = newSmoke.transform.Find("Image").GetComponent<Image>();

but the name is hardcoded so if you change the "Image" name, you should change it in the code too. Another way, would be:

imageArray[x, y] = newSmoke.GetComponentsInChildren<Image>()[1];

That asumes only the "GridSpace" and the "Image" GameObjects have Image component. Notice the "s" in GetComponentsInChildren.

Upvotes: 2

Related Questions