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*.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)

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 :slight_smile: