Fading objects to transparent - Apply shader with a script?

Hi,

I have a cube which has its box collider set to ‘is Trigger’ and a Rigidbody component (to make the Trigger work) which moves forward towards some stationary objects which also have box collider components.

I am going to have a camera moving towards these objects and want the objects to fade to transparent when they approach. For this, I have created a trigger that will cause any objects that collide with it to gradually become transparent. So far, the trigger detects the objects fine and on doing so creates a temporary renderer object to reference each object’s renderer. I then create a Color object with transparency to apply to their renderer.

Now, the objects change colour just fine but their alpha does not change. I have a suspicion that I have to use a shader for this, but am not sure how to apply one if this is the case.

Also, if anyone can suggest a more elegant method for fading objects approaching the camera then that would be great too. I would like to try to avoid using iTween as am trying to learn the ropes.

Thanks in advance.

void OnTriggerEnter(Collider theCollision)
{
    if (theCollision.gameObject.tag == "Obstacle")
    {
        Debug.Log("Trigger collided with an Obstacle");

        Color transparencyColor = new Color(1, 1, 1, 0.01f);

        Renderer tempRenderer;

        tempRenderer = theCollision.renderer;
        Debug.Log("tempRenderer.name = " + tempRenderer.name);

        tempRenderer.material.color = transparencyColor;

    }
    if (theCollision.gameObject.tag == "Player")
    {
        Debug.Log("Trigger collided with the Player");
    }
}

Try changing

tempRenderer.material.color = transparencyColor;

to

tempRenderer.material.color.a = 0.01f;

Does it work?

Hi Kevin,

Thanks for your suggestion, they both work which is great.

The main problem appeared to be that I needed to have a Transparent Shader type for the material applied to the Obstacles in order to change the Alpha value. I was using the default Diffuse Shader.