Question by
Borzi · Feb 24, 2016 at 03:18 PM ·
variablegetcomponentcastinggetcomponentsinchildren
Get instances of a script in children
Hello there! I am trying to run a script that allows me to access all instances of a script within the children of an object. To do this, I have tried the following:
//simplified script to pinpoint the issue
private Component hitBoxes;
void Update()
//get hitboxes in object
hitBoxes = GetComponentsInChildren<AIHitbox>();
foreach (AIHitbox hitBox in hitBoxes)
{ //call this function on each instance
hitBox.switchForcePos(true);
}
Thank you in advance!
Comment
You should change private Component hitBoxes; to private Component[] hitBoxes;
Best Answer
Answer by phil_me_up · Feb 24, 2016 at 03:45 PM
GetComponentsInChildren expects to return an array, where as you are trying to assign the result to 'hitBoxes', which is not an array.
Additionally, you are passing the type AIHitbox into the call to GetComponentsInChildren, but assigning it to a hitBoxes, which is a component.
Changing:
private Component hitBoxes;
to
private AIHitbox[] hitBoxes;
should fix your problems