- Home /
Rendering an entire object as transparent
I have a problem when I want a certain object to render as transparent. I previously solved the issue by looping through all renderers and their materials, making new materials for each material (but with a trannsparent rendering mode and with a bit less opacity). Though it doesn't feel right to create an entirely new material for each material in the object, so I thought that I'd make a narrower selection of materials (one for each colour) and the same selection of transparent materials. Making all materials transparent makes the object look a little weird in certain cases, because if two transparent materials are rendered behind one another, they overlap and both surfaces end up being visible. Is it possible to bypass this problem somehow? I thought of doing something like rendering the object alone using its own camera and then overlaying the picture on top of the screen, but more transparent, (which would make the object render in front of everything else though). I also thought, if there is a way to do this using shaders (though I cant use them yet).
Anyway, should I stick to replacing materials, or is there a way to render a GameObject and its children as transparent using shaders?
Answer by mafima · Nov 29, 2017 at 08:50 PM
Well, a Material is using 1 shader. this shader can have multiple textures and parameters, but ultimately 1 material uses 1 shader. there are shaders, that just make your object transparent, but you need to change your shader for that. so you COULD create 2 shaders and just change the shader for all your materials into the other transparent shader in your script. that way you dont create materials, but just replace shader.
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour {
public Shader shader1;
public Shader shader2;
public Renderer rend;
void Start() {
rend = GetComponent<Renderer>();
shader1 = Shader.Find("Diffuse");
shader2 = Shader.Find("Transparent/Diffuse");
}
void Update() {
if (Input.GetButtonDown("Jump"))
if (rend.material.shader == shader1)
rend.material.shader = shader2;
else
rend.material.shader = shader1;
}
}
https://docs.unity3d.com/ScriptReference/Material-shader.html
So it is possible to just replace the shader for each material and they will all render as transparent? If yes, how do I make such shader? (I never worked with them.)
if you have a correct shader, yes. but most of the shaders render something. it comes down to the question: what do you want to do? more performance? why dont you just change the alpha of the transparent material?
Alright, if I don't notice performance drops, I'll go with just creating new materials out of the old ones and transparifying them. One thing I've noticed though is that I can't directly replace the materials in the Renderer.materials array, but I had to replace the entire array, that's just a heads-up for anyone who has the same problem.