GetComponentInChildren doesn't work when instantiating object
So I have an enemy with a health bar. I have a script that manages enemy health. In the Start function I use GetComponentInChildren to get the Slider component. When I place the enemy in the scene and hit play, it works normally. But when instantiating the enemy object, which is how I want to do it, it doesn't work; the slider variable remains null. The weirdest part is that it worked before in other enemies using the same health script, but I can't figure out why it doesn't work with this one.
The enemy object is set up like this:
And this is my script:
void Start()
{
healthSlider = GetComponentInChildren<Slider>();
health = maxHealth;
healthSlider.maxValue = maxHealth;
}
Answer by BenWiller1989 · Sep 05, 2020 at 11:48 AM
I couldn't figure it out. Would you mind using gameobject.transform.Find("SliderObjectName").GetComponent(); and see if that works? Just put the GetComponent correctly, it's hard to show you here, because it will be used as a tag. This way, he'll only search the children of the script holder and get the Component your looking for. Please try that and see if it works.
That worked! I wrote that line like this:
healthSlider = transform.Find("Canvas/Slider").GetComponent<Slider>();
I still don't understand why it didn't work the other way, though :/ Thank you!!! (Sorry for the duplicate post, BTW. I don't know why it happened. I wasn't even awake 2 hours ago when this question was supposedly published)
Nice! So happy it worked for you! Still, very odd issue. Who knows why these questions duplicate. $$anonymous$$aybe to update unsolved automatically.
Your answer

Follow this Question
Related Questions
GetComponentInChildren doesn't work when instantiating the object 1 Answer
instantiate 1 Answer
Change color of object with C# 1 Answer
Gameobject array 0 Answers
Please Explain the Code 0 Answers