#how can i access meshrendrer of child gameobject and set a new material to t by code
1 messages · Page 1 of 1 (latest)
declare two mesh renderers in the parent and assign them in the inspector
public class Parent : MonoBehaviour
{
public MeshRenderer child1;
public MeshRenderer child2;
// Start is called before the first frame update
void Start()
{
child1.material = new Material(Shader.Find("materials/whatever"));
child2.material = new Material(Shader.Find("materials/whatever"));
}
// Update is called once per frame
void Update()
{
}
}
but sir there is a problem in that things
i have 99 child present in my object
my object is a cell fracture ball
Usually I would say to avoid the Get Component functions, but this seems like a good time to use Component.GetComponentsInChildren<>(). Note the name is “GetComponent__s__InChildren”, not “GetComponentInChildren”. “Components” is plural here.
Yeah sir i try to do it but i can not access mesh rendrer of chinldren
Can u explain in code
Its just one line of code? Meshrenderer[] arrayOfMeshes = GetComponentsInChildren<MeshRenderer>(). Have you not ever used arrays before?
used but its not working sir
It generates an array, which means you have to loop through it. My guess is that you're not, an that you're just trying arrayOfMeshes.material, etc.
Yeah sir i know about array
Store data and reveal we use for or foreach loop
But that's don't work sir
@sullen herald
make sure the script is on the right object and actually runs. Start etc. will only run if your object is active, and it's literally as simple as collecting your renderers in the children and setting the material
but if the objects have multiple materials, then you need to do some more work
Renderer[] renderers = GetComponentsInChildren<Renderer>();
foreach (Renderer r in renderers) {
r.sharedMaterial = yourNewMaterial;
}