- Home /
Change sprite's color without making an extra drawcall
I have multiple sprites (with SpriteRenderer component), and they share the same material. For assigning material I use this code:
renderer.sharedMaterial = AppSettings.MaterialSpriteDefault;
And if I change color in SpriteRenderer, nothing changes in the scene, sprite remains the same. But if I assign material like this:
renderer.materials [0] = AppSettings.MaterialSpriteDefault;
every sprite = extra drawcall, because Unity creates new instance of material for every sprite, and I'm trying to get rid of it. Any thoughts about how I can achieve desired behaviour?
How do you change the color? With the default sprite shader you're not getting additional drawcalls by changing tint.
I change color using spriteRenderer.color. If the material is shared - nothing happens in the scene, the color remains the same. If I change color to shader in shared$$anonymous$$aterial, it says "$$anonymous$$aterial doesn't have a color property '_Color' ". But if sprites have their own instance of material, shader's color is changing.
I did a little test, copying a sprite 15 times (16 total) with this piece of code on them
void Start () {
GetComponent<SpriteRenderer> ().color = new Color (Random.Range (0, 1f), Random.Range (0, 1f), Random.Range (0, 1f), 1);
}
One drawcall, 15 batches, changed color in game view. Don't know what you did wrong, but maybe that gives you the right hint.
This is really strange. I did the same in test scene and everything worked. But in my current scene it won't work for some reason. http://monosnap.com/image/fiZxquH8$$anonymous$$IeHw1D$$anonymous$$ggiAzNUPxGtHXk
Okay, for some reason the problem probably was in adding spriteRenderer component to gameObject manually from code. I dragged sprite into the scene, Unity created gameObject with spriteRenderer for me, I made prefab from it, and used it as template for my next sprites, and now everything works fine. Really weird behaviour.