Hi Guys, I’m new to Unity and I’m trying to work with Materials and alpha properties, but I’ve got a problem already…
I need to fade out an object that has several children (and some of those children also have sub children). When I Change the alpha of material of the main object in the editor, all sub objects (children) also get that new alpha value. The problem is that in runtime, using c#, I can’t make fadeout my object… I figured out that I needed to modify the alpha of all children so I did:
void changeAlpha(GameObject targetObj, newAlpha){
MeshRenderer[] all = targetObj.GetComponentsInChildren<MeshRenderer>();
for(int i=0; i<all.Length; i++){
Material cMat = all[i].renderer.material; // Get currentMaterial
all[i].renderer.material.color = new Color(cMat.color.r, cMat.color.g, cMat.color.b, newAlpha);
}
}
It’s working fine (well, not completely… some objects for some reason still don’t get the alpha), the problem is that it consumes a hell of resources, actually it freezes my computer some times. Probably because I’m calling the method several times per second, when a slider change its value. And also, there are up to 3 different objects to which I need to fade out at the same time…
It’s there any better way to do this? How the editor does it??
In my game I’m using a code thats similar to dood’s. The only difference is that my Material uses a shader that has _AlphaMod to change Material alpha.
But I’m not sure this is the best approach. It’s to my knowledge that everytime you make any change to a material (by script) it get duplicated so the change won’t affect all objects with the same material.
Btw, if you want to change the alpha/color of all objects that uses the same material, use this:
I’m not proficient in C# code so I haven’t noticed that he’s creating a new material every time but if that’s the case then that’s definitely what’s causing the slowdown.
Modifying material will change the material for this object only. If the material is used by any other renderers, this will clone the shared material and start using it from now on.
source: Unity - Scripting API: Renderer.material
Wow Guys, Thanks sooo much for all your replies. I just woke up and i’m about to test dodo’s approach. But beneton’s method looks pretty straight forward. BTW, I can’t believe I didn’t notice I was creating a material every frame!!! suddenly all my resource consumption make sense! Thanks for pointing that out kiberkiller.