Change the Transperency of a Prefab in Unity

2

I have three cubes (one in front of another) in a Unity scene and I would like it when a condition is given, the first cube would come out semi-transparent so that the one from the back could be seen.

I tried the following:

cubo1.GetComponent<Renderer>().material.color.a = 0.5f;

But I get an error. I have the cubes declared as follows:

public GameObject cubo1;

I changed the Material Shader from Standard to Legacy Shaders/Transparent/Diffuse for the Alpha channel theme, but nothing ...

Does anyone have any ideas?

    
asked by DarthDev 17.10.2016 в 13:02
source

3 answers

6

For whoever is interested, I have already solved it. Here the solution:

public GameObject cubo;

public void Transparente() //assignado a un button
{
    cubo.GetComponent<Renderer>().material.color = new Color(1, 1, 1, 0.3f); //llamo al canal alpha en el último valor (1=100%, 0.5f = 50%, 0 = 0%)
}

// Use this for initialization
void Start () {

    Material matTrans = new Material(Shader.Find("Transparent/Diffuse"));
    GetComponent<Renderer>().material = matTrans; //Crear nuevo material Transparente
}

I hope it helps if someone needs it!

    
answered by 18.10.2016 в 10:59
1

The Color structure you're accessing in

cubo1.GetComponent<Renderer>().material.color.a = 0.5f;

is a copy of the one in the material. So accessing only the property "a" would involve changing the alpha of the copy, and this gives you an error (something similar happens when you try to do transform.position.x = 5)

The correct way to modify the value in C # is as you have done in your answer, with the problem that you can overwrite or lose the other color values, or doing something like this:

Color c = cubo1.GetComponent<Renderer>().material.color;
c.a = 0.5F;
cubo1.GetComponent<Renderer>().material.color = c;

In this way you leave the previous values r, g, b intact, not as in your example.

Besides that, so that you can see the effects of the alpha change, the material must be of the "Transparent" or "Cutout" type, as you have already been told.

I hope it works for you ^^

    
answered by 21.05.2017 в 15:38
0

You can also modify the material, Above you see it says transparent .

Look at this example:

    
answered by 03.05.2017 в 00:03