0
\$\begingroup\$

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

\$\endgroup\$
4
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ 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? \$\endgroup\$ – ErezProductions Aug 9 '15 at 23:17
  • \$\begingroup\$ I did what you said, how ever I still see the objects. Does it work with rigidbody component? \$\endgroup\$ – ErezProductions Aug 10 '15 at 0:34
  • \$\begingroup\$ 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. \$\endgroup\$ – Greg Quinn Aug 10 '15 at 4:26
  • \$\begingroup\$ 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. \$\endgroup\$ – ErezProductions Aug 10 '15 at 12:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.