- Home /
Prefenting materials[].SetColor from making Instances
Hello. I have an object with several Material Slots and on one of those i would like to change its Color. To keep Draw Calls low, I know that I need to prevent Instances of the Material otherwise unity wont be able to batch those dynamically. Anyway, this is the little Script i use to search for the Material Slot and do set its color.
public class MaterialInstanceTester : MonoBehaviour
{
public Color targetCol = Color.white;
private int matSlot;
void Start ()
{
//Get a copy of the Materials array
Material[] myMats = gameObject.GetComponent<Renderer> ().sharedMaterials;
//Search for the Material we like to find its "slot" number in the array
for (int i = 0; i < myMats.Length; i++)
{
if(myMats[i].name.StartsWith("test"))
{
matSlot = i;
}
}
//Now we make an Instance of the selected Material
gameObject.GetComponent<Renderer> ().materials[matSlot].SetColor("_Color", targetCol);
//The job is done, remove the Script
Destroy (this);
}
}
Sadly this doesn't work and it makes regardless Instances of all Materials on the Gameobject. Here comes the interesting part, if I replace
gameObject.GetComponent<Renderer> ().materials[matSlot].SetColor("_Color", targetCol);
with this:
gameObject.GetComponent<Renderer>().material.SetColor("_Color", targetCol);
then it will make only an instance of the first Material Slot and leave all the others alone. This obviously useless to me since i want to change an other Material Slot and not the first one.
So yeah, does anyone have an Idea how i can change a specific Material Slot without making instances of all Materials)
Answer by garrido86 · Mar 17, 2015 at 09:18 PM
Alright i found my solution, i just needed to change
gameObject.GetComponent<Renderer> ().materials[matSlot].SetColor("_Color", targetCol);
to this:
myMats[matSlot].Color = targetCol;
gameObject.GetComponent<Renderer> ().materials[] = myMats;
myMats = null;
Now it works perfectly without any Material instancing and I get nice dynamic batching :)
Your answer
Follow this Question
Related Questions
Changing the material in an array of materials at run time 2 Answers
How to replace materials in the materials array 3 Answers
Collada import material Main Colors 0 Answers
Is there a way to export animated UVs from a 3d package? 2 Answers
Any suggestions on this approach to multiple objects and materials 0 Answers