- Home /
Make a custom 3d mesh object opaque and transparent
Hello everyone,
I am very new to Unity3D and C#. I am making a simple application that changes the transparency of the object (as shown in attachment). When I use the Albedo manually it does the great job, but I want to achieve the same thing with the help of a button. That means when the button is clicked, I get the to make the object opaque or transparent through script.
I've seen a lot of code such as gameobject.GetComponent<Renderer>().material.color
... and so on but nothing seems to work when I click the button. I don't get any errors either
I'd be grateful if someone can help me achieving the Alpha value from 255 to 0 or vice versa on button click event.
Thank you in advance, Cheers!
Answer by Cherno · Aug 11, 2017 at 03:22 PM
Let your button call this method:
Renderer renderer;//drag object here in the inspector
public void SwitchTransparency() {
material mat = renderer.material;
float alpha = mat.color.a;
if(alpha == 0) {
alpha = 1;
}
else {
alpha = 0;
}
mat.color = new Color(color.r, color.g, color.b, alpha);
renderer.material = mat;
}
Hey Cherno,
I am getting some errors
atNullReferenceException: Object reference not set to an instance of an object
$$anonymous$$aterial mat = renderer.material;
The code I am using is: public class SwitchTransparency : $$anonymous$$onoBehaviour { Renderer renderer; Color color; GameObject obj;
public void SwitchingTransparency() { obj = GameObject.Find("Heizkoerper_Zusammen"); $$anonymous$$aterial mat = renderer.material; float alpha = mat.color.a; if (alpha == 0) { alpha = 1; } else { alpha = 0; } mat.color = new Color(color.r, color.g, color.b, alpha); renderer.material = mat; }
}
I think I am missing this step og dragging object in inspector like you told.
The variable called "renderer" needs to hold a reference to the Renderer, of course, and that Renderer also needs to have a $$anonymous$$aterial assigned to it. Hence the comment line.
Your answer
Follow this Question
Related Questions
Does the Particle Animator work with transparent shaders? 1 Answer
Different transparency on same texture? 1 Answer
Texture transparency not working as expected 3 Answers
transparent RGBA PNG textures worked in 4.6, how can I get them working in Unity5? 1 Answer
use Alpha from image in Fragment shader 0 Answers