Filled image only updating when not a child item

Hello,
On my canvas I have an image (in the image below ‘UI_HealthBar_Prefab’) with a child image (‘health_bar_filling’). The child is set as a filled image from 0…1.

For the parent I have attached some code to update the fillamount. However on testing it’s not working because in my code:
void Start () {
fillingImage = GetComponentInChildren();
UpdateHealthBar();
}

fillingImage is picking the image associated with itself, i.e. the parent.

I thought this would work. If I attach the code to the child it works fine, but I want to attach it to the parent. How do I stop the parent image from being part of the method call?

2998678--223503--Untitled.png

I found two solutions but both seemed a bit crap:

  1. I made the ‘filledImage’ a public and added it directly
  2. I followed this thread GetComponentInChildren Returning a Component in Parent - Questions & Answers - Unity Discussions and ignored the first item

Is there not a better way? e.g. a flag to say don’t include me in searches or to only actually search children?

thanks.

The first solution is good, though I would make the variable private and use SerializeField attribute. That way there is no hidden dependency to the hierarchy.

Anyway, I don’t think there’s such a flag. What you could do, is to create an extension method that does take a flag.

Thanks, I’ve gone with the simpler first option :slight_smile: