- Home /
Changing material at runtime of a meshrenderer won't work
When I change during runtime the material of a mesh renderer with another material using the same shader, the properties of my material stay at the same value as the former material but the name of the material of the meshrenderer is updated.
I tried
obj.GetComponent().mat = newMat;
or
obj.GetComponent().mat.color = newMat.color;
or
obj.GetComponent()..material.SetColor("_Color", newMat.color);
I don't understand how it works
Answer by digvijay027 · Apr 07, 2021 at 09:30 AM
You can't change directly a material in the material array of the object. You need to get the array. Try below solution.
MeshRenderer myRendMat; void Start() { myRendMat = transform.GetComponent(); ChangeColor(); }
private void ChangeColor()
{
Material[] material = myRendMat.materials;
material[0].color = Color.red;
}
Answer by EliasMiettinen · Apr 07, 2021 at 08:32 AM
Test this:
obj.GetComponent().material = newMaterial;
or
obj.GetComponent().material.color = Color.green; // Or something that you want
Your answer
![](https://koobas.hobune.stream/wayback/20220613031553im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Material is not visible in android build but works fine in editor? 0 Answers
Accidentally assigned shader to default sprite material, how to revert it back to Sprites/Default? 0 Answers
Sequential shaders. Pass the output color of a shader to the next one. 0 Answers
how can I set multiple materials to a mesh ? 0 Answers
Problem with overlapping cubes 0 Answers