The GetComponentsInChildren()
function 'Returns all components of Type type
in the GameObject or any of its children. Works recursively.'
If the code is executed by the parent GameObject, and it has an Image
component, this is likely to be the one returned by the function in your case (since no order criteria are mentioned in the reference page).
Referencing GameObjects via Inspector fields isn't an in-editor workaround–it's an intended feature for programmers to use. You can get a reference via code, but it isn't going to be easy if the intended GameObject lies deep down a hierarchy. Otherwise, you can just reference it via Inspector fields and be assured that's the object or Component your code is going to reference.
If you want to keep a long-term reference to an object, you may want to search it by its name. GameObject.Find()
does exactly that. Even better, you can look for a child GameObject via Transform.Find()
:
referenceImage = transform.Find("Image").GetComponent<Image>();
GetComponentsInChildren<Image>()[1]
gets you the second image component in the children. Are you sure you want that? To get the first image component in the children, you would get the array index[0]
. Or even simpler, use the methodGetComponentInChildren<Image>()
(no "s" between "Component" and "In"). It gets you the first component it finds. \$\endgroup\$referenceImage
? If so, what image do you get instead? Do you get null? Do you get an array access out of bounds error? These details are important for users to be able to diagnose the problem. \$\endgroup\$