- Home /
Exception when I try to get other parent's children (GameObjects)
Good day to ya. I had an empty parent GameObject and a script, attached to every child GameObject.
In this script I'am trying to do next:
GameObject[] children = this.GetComponentsInParent<GameObject>()
And i have this exeption:
"ArgumentException: GetComponent requires that the requested component 'GameObject' derives from MonoBehaviour or Component or is an interface."
What I'am doing wrong?
Answer by Dragate · Oct 12, 2017 at 07:25 PM
Gameobjects are not components, they are containers for components. You can't get Gameobjects in such fashion. Since your child is related to the other gameobjects by their transform, you can get them with this code:
Transform parent = transform.parent;
GameObject[] children = new GameObject[parent.childCount];
for(int i = 0; i < parent.childCount; i++){
children[i] = parent.GetChild(i).gameObject;
}
Answer by gnp89 · Oct 12, 2017 at 07:26 PM
GameObject does not inherit from Component. So you can't use GetComponentsInParent.
What you need here is:
Transform parent = transform.parent; // access this GameObject's parent
for (i = 0; i < parent.GetChildCount(); i++){
Transform child = parent.GetChild(i);
}
Your answer
Follow this Question
Related Questions
Get Children of Child and Deactivate/Activate on Demand 1 Answer
Problem with prefab parent and children objects that need to be instantiated multiple times. 1 Answer
Parent/Player teleports but its children dont teleport aswell 4 Answers
sending a message to child objects 2 Answers
Add Pointer Down event trigger only to parent object. 1 Answer