Reputation: 99
I see this subject in stack over flow but I think it is false 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.
How I can use:
gameObject.GetComponent<Renderer> ().material.color.a = 0;
Upvotes: 9
Views: 78859
Reputation: 10561
Transparent
.Then, add the below script.
using UnityEngine;
public class MakeTransparent : MonoBehaviour { public GameObject currentGameObject; public float alpha = 0.5f;//half transparency
void Start()
{
currentGameObject = gameObject;
}
void Update()
{
ChangeAlpha(currentGameObject.GetComponent<Renderer>().material, alpha);
}
void ChangeAlpha(Material mat, float alphaVal)
{
Color oldColor = mat.color;
Color newColor = new Color(oldColor.r, oldColor.g, oldColor.b, alphaVal);
mat.SetColor("_Color", newColor);
}
}
Change the alpha value in the inspector on runtime.
Here is the video explanation.
Upvotes: 0
Reputation: 3
Try in this way
var other : GameObject;
other.renderer.material.color.a = 0.5f; // 50 % transparent
other.renderer.material.color.a = 1.0f; // 100% visible
Upvotes: -4
Reputation: 631
For those who might still come across this question, gameObject.GetComponent<Renderer> ().material.color
is not a variable. Create a variable as such:
var trans = 0.5f;
var col = gameObject.GetComponent<Renderer> ().material.color;
Then assign your value:
col.a = trans;
Also be aware that not all shaders have a _Color
property. In my case, I had to use:
var col = gameObject.GetComponent<Renderer> ().material.GetColor("_TintColor");
Upvotes: 12
Reputation: 5353
How I can use:
gameObject.GetComponent<Renderer> ().material.color.a = 0;
As you already stated in your own question, the object you call this on must have a shader which supports transparency. In Unity5, when using the standard shader, you must explicitly set it to "Transparent" to be able to manipulate the alpha value.
It should also be clear to you that the alpha value is a float
which goes from 0.0f
to 1.0f
, so e.g. setting
gameObject.GetComponent<Renderer> ().material.color.a = 0.5f;
will make the object 50% transparent.
Upvotes: 3