0
\$\begingroup\$

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];
}

enter image description here

\$\endgroup\$
2
  • \$\begingroup\$ 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. \$\endgroup\$
    – Philipp
    Oct 20, 2021 at 7:43
  • \$\begingroup\$ 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. \$\endgroup\$
    – DMGregory
    Oct 20, 2021 at 11:51

1 Answer 1

1
\$\begingroup\$

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>();
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .