- Home /
Turning standard materials from opaque to transparent and back in runtime
I have made a system that detects all objects that are in-between the camera and gives them transparent properties when they are not gives back their normal ones, it works like a charm in the editor but when I build the project transparency stops working. Here's the script that turns them transparent:
foreach (var mat in a.renderer.materials)
{
mat.SetFloat("_Mode", 3);
mat.SetColor("_Color", new Color(mat.color.r, mat.color.g, mat.color.b, 0.3f));
mat.renderQueue = 3000;
mat.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
mat.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
mat.SetInt("_ZWrite", 0);
mat.DisableKeyword("_ALPHATEST_ON");
mat.EnableKeyword("_ALPHABLEND_ON");
mat.DisableKeyword("_ALPHAPREMULTIPLY_ON");
}
and this one turns them back into opaque:
foreach (var mat in a.renderer.materials)
{
mat.SetFloat("_Mode", 0);
mat.SetColor("_Color", new Color(mat.color.r, mat.color.g, mat.color.b, 1f));
mat.renderQueue = 2000;
mat.SetInt("_SrcBlend", 1);
mat.SetInt("_DstBlend", 0);
mat.SetInt("_ZWrite", 1);
mat.EnableKeyword("_ALPHATEST_ON");
mat.DisableKeyword("_ALPHABLEND_ON");
mat.EnableKeyword("_ALPHAPREMULTIPLY_ON");
}
I'm not familiar with materials and shaders so all help will be appreciated
Answer by Cornelis-de-Jager · Nov 27, 2018 at 09:56 PM
Hi @punsho , to achieve that what you will need to do is have all your materials have the Transparency on the shader. Next step is to access each material like you do. Then its simply changing the alpha value in the colour property
foreach (var mat in a.renderer.materials)
{
mat.color.a = 0.5; // 50 % transparency
mat.color.a = 1; // 100% transparency
}
var other : GameObject; other.renderer.material.color.a = 0.5; // 50 % transparent other.renderer.material.color.a = 1.0; // fully opaque
no that doesn't work properly, I have already tried that and I know that transparent materials with alpha value of 1 render incorrectly
this is how it looks when opaque this is how it works when transparent with an alpha value of one 1
Your answer
Follow this Question
Related Questions
Shader for distorting a texture as if it were on a sphere 3 Answers
Adding object to scene causes problem with other objects material/shader 0 Answers
How do I make a water shader that has depth. 1 Answer
See backside of a transparent emissive shader? 0 Answers
Night Vision shader is interacting weird between the level's mesh and the spotlight 0 Answers