# How to change the transparency of an object in Unity c# scripting?

I have laser-object in my scene, which I want to be seen only when I press the 'E' button on the key board(just an example of a key). I have seen many ways to change the transparency , however, none of them worked. one of them was -

gameObject.renderer.material.color.a = 0.0f ;


I get an Error - UnityEngine.renderer does not contain color and material sub-functions.

I don't know how to do it, and I tried many ways. Does someone have an easy way to make an object transparent and visible in C# script ? Thank you

Making an object 'transparent' so it cannot be seen is not the most efficient way to do things. What you rather want to do is make the renderer inactive when you don't want to see it, and active when you do.

If you click on your gameObject in the editor, there should be a Mesh Renderer as one of the components.

To set it to inactive from a script attached to this same gameObject, you can do this...

gameObject.GetComponent<Renderer> ().enabled = false;


If you really want to use transparency, you can do this...

gameObject.GetComponent<Renderer> ().material.color.a = 0;


Although if you are setting transparency, you need to make sure the shader the material is using supports transparency. I would suggest using the Legacy Shaders/Transparent Diffuse shader.

• So all I need to do is use this line code(the renderer disabled) - 1 time when I want to see, and 1 time when I dont want? Is that all? – ErezProductions Aug 9 '15 at 23:17
• I did what you said, how ever I still see the objects. Does it work with rigidbody component? – ErezProductions Aug 10 '15 at 0:34
• A rigidbody component and a renderer component are two different things. You need to run the script on a gameobject that has a renderer component such as Mesh Renderer etc. It is this component that lets you see the object. – Greg Quinn Aug 10 '15 at 4:26
• I have done that and it works, however, when I tried to do this again but with the Box Collider, the box collider component isn't turning off even though it is written in the script. – ErezProductions Aug 10 '15 at 12:33