- Home /
Change the material ELEMENT on an Object in a script?
My object has multiple elements (e.g. element 0 is darkblack, element 1 is black, element 2 is black)
How would I make it so that, when a collision is registered, it changes element 0 to, lets say, white?
I tried:
public Material WhiteMaterial;
public Material DarkBlackMaterial;
public GameObject Object;
void OnCollisionEnter (Collision Current)
{
Object.GetComponent<MeshRenderer>().material = WhiteMaterial;
}
But that didn't seem to work. Any ideas if that's because it has 3 elements of materials or is there something else I need?
Answer by Bunny83 · Nov 10, 2021 at 01:47 PM
When you have a mesh with submeshes and therefore multiple materials on a single renderer, you have to use the materials / sharedMaterials properties (not the plural). However those are properties and in order to change the materials you have to "assign" an array to the property. So generally you would need to do:
var renderer = Object.GetComponent<MeshRenderer>();
Material[] materials = renderer.sharedMaterials; // read current array of materials
materials[0] = WhiteMaterial;
renderer.sharedMaterials = materials; // assign the array back to the property to actually apply the changes
Note when you use the material or materials property Unity will create a dedicated material instance for this renderer. So when you want to replace materials that should be shared (to benefit from batching) you should use sharedMaterial / sharedMaterials.
Your answer
Follow this Question
Related Questions
Can you trick a Ui Button that it is being clicked with code? 3 Answers
problem with collision and trigger 1 Answer
How do I use collisions for player/enemy interaction 2 Answers
Why does reading MeshRenderer.material change MeshRenderer.sharedMaterial? 1 Answer
How to render a sprite to a quad? 1 Answer