- Home /
when does a new material instance get created
lets say i have something like this :
function Update(){
ch_spriteRenderer.color.a -= fadeAmount;
ch_spriteRenderer.color.g -= greenBlueFade;
ch_spriteRenderer.color.b -= greenBlueFade;
ch_spriteRenderer.color.r -= redFade;
}
Does this mean that FOR EVERY SINGLE FRAME, FOR EVERY SINGLE LINE, A NEW MATERIAL INSTANCE IS GENERATED FOR THE OBJECT CONTAINING THE SCRIPT?
as in 4 new materials instances every frame?
which would of course continously break batching correct?
Well... if you don't want it to be called 4 times in this instance you can cache the color, modify it, and then apply the new color one time only:
Color targetColor = ch_spriteRenderer.color;
targetColor.a -= fadeAmount;
targetColor.g -= greenBlueFade;
targetColor.b -= greenBlueFade;
targetColor.r -= redFade;
ch_spriteRenderer.color = targetColor;
Yes. http://docs.unity3d.com/$$anonymous$$anual/EventFunctions.html
Answer by robertbu · Nov 17, 2014 at 04:33 PM
To answer your specific question, you will only get a new material instance once...the first time you change any material property. After that, your object will use the same material instance. To demonstrate, run this:
#pragma strict
private var mat : Material;
function Start() {
mat = renderer.sharedMaterial;
}
function Update () {
if (mat != renderer.sharedMaterial) {
Debug.Log("Material different");
mat = renderer.sharedMaterial;
}
renderer.material.color = Color(Random.value, Random.value, Random.value);
}
Which means there's no point in doing what the guy above said right? Color targetColor = ch_spriteRenderer.color; targetColor.a -= fadeAmount; targetColor.g -= greenBlueFade; targetColor.b -= greenBlueFade; targetColor.r -= redFade; ch_spriteRenderer.color = targetColor;
since it already creates a new instance the first time.
Then again im a little confused.
I cache the renderer, but i don't cache the material. does it call getComponent on the material every time?
should i run the if statement to assign the new instanced material as a reference?
i can just do what the guy above commented, have a color variable to copy the renderer color, then apply all changes and copy it back. Seems like a decent solution.
$$anonymous$$atherial is not a component, so there is no GetComponent() call. But I'm relatively sure there is a $$anonymous$$atherial.GetColor() each time a color is accessed and a $$anonymous$$aterial.SetColor() call under the hood each time you assign to $$anonymous$$aterial.color. So @Wisearn's suggested code makes sense to me. You'd have to run a performance test to be absolutely sure.
Your answer
Follow this Question
Related Questions
Changing two different objects renderer colour 1 Answer
Question about batching and SRP 2 Answers
Low FPS despite simple scene 3 Answers
Reduce Draw Call for Sprite 1 Answer