- Home /
Apply materials or components to children?
I have a script that instantiates an object that has four children, and I'm trying to change the color of each one individually, but that means I also have to apply a mesh renderer to each child. The system right now is the parent object gets instantiated with a script that should change its children. Any help is greatly appreciated. Thanks!
Answer by Llama_w_2Ls · Aug 18, 2020 at 04:30 PM
public GameObject ParentToInstantiate;
void InstantiateObjectAndAddMeshRendererToAllChildren()
{
GameObject Parent = Instantiate(ParentToInstantiate, Vector3.zero, Quaternion.identity);
//Instantiates a gameobject at (0, 0, 0) with default rotation
Transform[] Children = Parent.GetComponentsInChildren<Transform>(); //Creates an array of all transforms within its children
foreach (Transform child in Children) //Anything that you want applied to all children in the parent object goes in here
{
child.gameObject.AddComponent<MeshRenderer>(); //Adds a mesh renderer to all children within the parent object
}
}
This is a simple way of applying changes to all children in an efficient way @Kolalamonkeys
@Llama_w_2Ls That works perfectly! How would I apply a material to just one of the children? Thanks!
Well all the children are in the array Transform[] Children so you could find one of the children in that array by typing Children[1] to get the second element in the array etc. (Remember that Children[0] is the first element and I think that that's the parent and not really any of the children). Finally, you could go Children[1].GetComponent<$$anonymous$$eshRenderer>().material = ... to change the material of one of the elements in the array. Hope you figure it out! @Kolalamonkeys
Your answer