- Home /
Changing material color creates a memory leak
I am creating a simple game, where multiple prefab clones exist, and when the mouse is over a specific clone, the material color of the clone changes.
public Renderer[] childrenRenderers;
private Color startColor;
[SerializeField] private Material defaultMaterial;
[SerializeField] private Material transparentMat;
// Use this for initialization
void Start () {
GetComponents();
}
void GetComponents (){
childrenRenderers = GetComponentsInChildren<Renderer> ();
foreach(Renderer rend in childrenRenderers){
rend.material = setDefaultMat();
}
//both materials have the same color, so we chooce randomly the first.
//startColor is the default material color that the turbine has.
startColor = defaultMaterial.color;
}
public void UndamagedHighlightMat (){
foreach(Renderer rend in childrenRenderers){
rend.material = setDefaultMat();
//rend.material.color = Color.cyan;
rend.material.SetColor("_Color",Color.cyan);
}
}
public void UndamagedDefaultMat (){
foreach(Renderer rend in childrenRenderers){
rend.material = setDefaultMat();
rend.material.color = startColor;
}
}
public Material setDefaultMat(){
return defaultMaterial;
}
When the mouse is over the UndamagedHighlightMat () is called and when not the UndamagedDefaultMat ().
I have tried many things like using sharedMaterial, but that changed every clone's material and not the specific one I wanted. Also, I found out that the problem was starting when the color was changing because the total number of objects in the profiler was increasing every time the material color changed.
So any help on the topic will be greatly appreciated, thank you in advance.
Have you tried a simple for loop ins$$anonymous$$d of the for each ? How do you get the childrenRenderers
? Can you provide the setDefault$$anonymous$$at
function ? (edit your question)
Answer by AurimasBlazulionis · Mar 25, 2017 at 02:55 PM
I would have a uninitialized material array. Let's say it is mats
. Once you get the components, create althe array like this: mats = new Material[childRenderers.Length]
. Then use a simple for(int i =0; i < childRenderers.Length; i++)
loop. Inside it set mats[I]
to the default material's copy (replace that function with return (Material)Object.Instantiate(defaultMaterial);
). Now do childRenderers[i].sharedMaterial = mats[i]
. And when you want to change the color edit iterate through the mats array or just through sharedMaterial. If you do the latter, you might not even need the array. You will just need to modify the setDefaultMat function.