Home > other >  Unity: Make color of MeshRenderer transparent
Unity: Make color of MeshRenderer transparent

Time:06-08

I have a little question. I have a cube which has a Mesh Renderer and I gave it a default black material as its color. Now I would like to make the object more transparent when it touches something. I already set the Rendering Mode to Fade or Transparent. The tag is also set. This is my code:

public GameObject cube; 
private Color tempcolor; 
void Start()
{
    tempcolor = cube.GetComponent<MeshRenderer>().material.color;   
}
public void OnTriggerEnter(Collider other)
{
    if (other.CompareTag("Object"))
    {
        tempcolor.a -= 0.1f; 
    }
}

My code doesn't do the job. When I Debug.Log tempcolor.a it goes down but nothing happens with the cube. I also tried normal Renderer but it didn't work. Any idea?

I would be grateful if you can help me out

Kind regards

CodePudding user response:

You don't need tempColor and Start() event, just save the main component temporary.

public void OnTriggerEnter(Collider other)
{
    var meshRenderer = cube.GetComponent<MeshRenderer>();
    
    if (other.CompareTag("Object"))
    {
        var color = meshRenderer.material.color;
        color.a -= .1f;
        meshRenderer.material.color = color;
    }
}
  • Related