Change Transparency

Hello,

Im in need of assistance. I came across this code in the unity documentation which turns objects transparent when hit with a raycast, and inserted it into my own game. However im unsure how i would efficiently go back to switching the objects that have been turned transparent back into being solid. Any help would be greatyl appreciated.

Thanks!

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour
{
    void Update()
    {
        RaycastHit[] hits;
        hits = Physics.RaycastAll(transform.position, transform.forward, 100.0F);

        for (int i = 0; i < hits.Length; i++)
        {
            RaycastHit hit = hits*;*

Renderer rend = hit.transform.GetComponent();

if (rend)
{
// Change the material of all hit colliders
// to use a transparent shader.
rend.material.shader = Shader.Find(“Transparent/Diffuse”);
Color tempColor = rend.material.color;
tempColor.a = 0.3F;
rend.material.color = tempColor;
}
}
}
}

1 Answer

1

Cache the original material and switch back to it in an appropriate situation.

new private Renderer renderer;
private Material originalMaterial;
private Material transparentMaterial;
private bool isShowingTransparentMaterial = false;

private void Awake()
{
  renderer = ...;
  originalMaterial = renderer.sharedMaterial;
  // Set up the transparent Material here
  transparentMaterial = new Material(Shader.Find( ... ));
}

private void Update()
{
  var shouldShowTransparentMaterial = Physics.Raycast( ... );

  if (shouldShowTransparentMaterial != isShowingTransparentMaterial)
  {
    if (shouldBeTransparent)
    {
      renderer.sharedMaterial = transparentMaterial;
    }
    else
    {
      renderer.sharedMaterial = originalMaterial;
    }

    isShowingTransparentMaterial = shouldShowTransparentMaterial;
  }
}