# Can't reference UI Image in Script

I'm making an inventory system for my game, part of that is updating the icon when the slot is full. For some reason, I can't reference the image component on the child UI image component. I've tried linking it in the prefab GO for the slot prefab, I've tried the script below. Doesn't seem to work. It works when I drag the child onto the parent GO script. Just not in code? Am I missing something? All help is welcomed.

void Start()
{
referenceImage = GetComponentsInChildren<Image>()[1];
}


• Arrays in C# start with 0. So 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 method GetComponentInChildren<Image>() (no "s" between "Component" and "In"). It gets you the first component it finds. Oct 20 '21 at 7:43
• Can you tell us specifically how this fails to work? Do you get the wrong image in 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. Oct 20 '21 at 11:51

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