I’m pretty new to Unity still, I have a multi-layered material where I need to remove one of the textures of the material during runtime. I don’t want to waste memory setting a new clear texture. Can anyone point me in the right direction?
I should note, using Destroy on a layer seems to destroy the entire material. For example:
Destroy(gameObject.renderer.materials[1].mainTexture);
If I do this:
gameObject.renderer.materials[1].mainTexture = new Texture2D(1,1);
it works, but may be a waste of memory. Open to something better. Thanks.
1 Answer
1
This isn’t really one “multilayered material” but simple two materials attached to the same renderer. That simply means the object is drawn twice, one time with the first material and one time with the second. You also don’t replace / remove the material, you just set a new texture fot the material.
Multiple materials are usually used when your Mesh contains submeshes, so each material corresponds to a submesh. If there’s only one submesh in the mesh it is simply drawn twice.
To remove the second material you have to replace the materials array and only include those materials you want to keep:
// C#
Material[] tmp = gameObject.renderer.materials;
gameObject.renderer.materials = new Material[] {tmp[0]};
May i ask why there are actually two materials when you want to remove one at runtime? I don’t get the point.
A 1x1 texture really does use 4 bytes plus overhead. It isn't grown to 512x512, for example.
– Owen-ReynoldsThanks Owen, this is good to know. I come from other game engines where this would not be true.
– SinisterRainbowMust be based on pre-graphics card code. For example, at least until a few years ago, visual C# ("Forms") hand-blended pixels -- something a graphics card does much much faster. A modern graphics card wants to rescale all textures. If you draw an X by X texture over exactly X by X screen pixels, it still scales by 1.0 and does all the adjacent pixels math. Any "modern" game engine will probably take advantage of auto-rescaling.
– Owen-Reynolds