2
votes

I want to enable a health bar canvas, which is a child of my enemy. I don't know how to access a component of a children.

The script is attached to a 'FightController'. I will find the enemies by their tag. The enemy-GameObject have each a 'Health bar'-GameObject.

void Start()
{
    enemy = GameObject.FindGameObjectsWithTag("enemy");

    for(int enemyNumber = 0; enemyNumber < 5; enemyNumber++){
         enemy[enemyNumber].GetComponentInChildren<Canvas>().enabled = true;  //This is not working.
    }
}

I get following error: 'NullReferenceException: Object reference not set to an instance of an object'

1
Well, you could try to use transform.GetChild[0].GetComponent<Canvas>() and make sure it isn't null. Of course if the canvas is the nth children of your enemy then use GetChild[n] instead of 0Michał Gryniuk
Cool thanks! This is working. You can answer it directly, so I can give you the star.Questioner123123

1 Answers

0
votes

Well, you could try to use transform.GetChild[0].GetComponent<Canvas>() and make sure it isn't null. Of course if the canvas is the nth child of your enemy then use GetChild[n] instead of 0.

Copied from my comment