UnityGameProjectsCode / RelianceGame / Camera Control / MakeTransparent.cs
MakeTransparent.cs
Raw
using UnityEngine;

public class MakeTransparent : MonoBehaviour
{
    private Renderer wall;
    public Material transparentMat;
    public Material originalMat;

    void Update()
    {
        RaycastHit hit;
        var camera = Camera.main.transform;
        Ray ray = Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));
        Debug.DrawRay(camera.position, camera.forward * 200, Color.red);

        if (Physics.Raycast(ray, out hit))
        {
            if (hit.collider.CompareTag("Wall"))
            {
                Debug.DrawLine(camera.position, hit.point, Color.yellow);

                if (wall != null)
                {
                    if (hit.collider.gameObject.GetComponent<Renderer>() != wall)
                    {
                        TurnOpaque();
                        wall = hit.collider.gameObject.GetComponent<Renderer>();
                    }
                }
                else
                {
                    wall = hit.collider.gameObject.GetComponent<Renderer>();
                }

                TurnTransparent();
            }
            else //if the object you hit is not a wall
            {
                if (wall != null)
                {
                    TurnOpaque();
                    wall = null;
                }
            }
        }
    }

    public void TurnTransparent()
    {
        wall.material = transparentMat;
    }

    public void TurnOpaque()
    {
        wall.material = originalMat;
    }
}