How to iterate through UI children

Hi

I want to iterate through UI children (in my case several RawImage objects). ‘Old’ approach

        foreach (Transform child in testObject.transform)
        {
//items is a List<RawImage>
            items.Add(child);//doesn't work
            items.Add((RawImage)child);//doesn't work
            items.Add((RawImage)child.gameObject);//doesn't work
        }

Doesn’t work for me when I try to iterate through 4.6 UI elements: I can’t cast transform/gameObject to RawImage.

How can I do it or what do I do wrong?

of course you can’t case a transform or gameObject to RawImage. RawImage doesnt derive from either of those… RawImage is a component on a GameObject the same way that Transform is a component. You’d need to GetComponent

Do you mean something like that:

RawImage ri = child.gameObject.GetComponent<RawImage>();
RawImage ri = child.GetComponent<RawImage>();

Forgot to say that both give null

foreach (Transform child in testObject.transform) {
   var rawImage = child.GetComponent<RawImage>();
   if (rawImage) {
      items.Add(rawImage);
   }
}

This way, if a RawImage is on the child, it will be added to the list.

BenZed: like I wrote above it doesn’t work for me (I get null for all children and I have only RawImage children).

Then the problem is originating from somewhere else! I’d make sure that testObject assigned correctly, otherwise upload your scene so we can take a closer look.

In a new scene everything works. After that when I recreated RawImage objects in my old scene it started to work. Don’t know how and why and I don’t care :slight_smile: Just another lesson for the future (after restarting Unity).
Thanks for help :slight_smile: