#how can i access meshrendrer of child gameobject and set a new material to t by code

1 messages · Page 1 of 1 (latest)

tawdry hill
#

i have a ball object that content two sphere in its child i wanna to add matrial to it by script but for that i have to get access of mesh rendrer of child how can i do that

rotund fractal
#

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()
    {
        
    }
}
tawdry hill
#

but sir there is a problem in that things

#

i have 99 child present in my object

#

my object is a cell fracture ball

modern galleon
#

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.

tawdry hill
#

Yeah sir i try to do it but i can not access mesh rendrer of chinldren

#

Can u explain in code

modern galleon
#

Its just one line of code? Meshrenderer[] arrayOfMeshes = GetComponentsInChildren<MeshRenderer>(). Have you not ever used arrays before?

tawdry hill
#

used but its not working sir

sullen herald
tawdry hill
#

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

ornate goblet
# tawdry hill <@919060552590979092>

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;
}