How can I affect an object, but only while it's being hit by a raycast?

Hello!

What I’m trying to do is make it so that certain objects in my scene will turn transparent while they are obstructing the camera’s view of the player. My current method is as follows:

  • Raycast from the camera’s position and in the camera’s orientation
  • If the object the ray hits is tagged with a specific tag, switch that object over to a transparent material.

While this works for turning those objects transparent when I need them to be, I’m not sure what I should do to switch them back to their non-transparent material. Any tips?

One way to do it would be to switch a boolean every frame, depending on its transparency.

using UnityEngine;
using System.Collections;

public class MyClassThatNeedsToGoTransparent : MonoBehaviour {

	public bool isObstructingPlayer = false;
    private bool isTransparent = false;

	private void LateUpdate () {
		if(!isTransparent && isObstructingPlayer) {
                //Do stuff to make it go transparent

                isTransparent = true;
		} else if(isTransparent && !isObstructingPlayer) {
		    //Do stuff to turn it back to normal

                 isTransparent = false;
		}

		isObstructingPlayer = false;
	}
}

[RequireComponent(typeof(Camera))]
public class MyCameraThatChecksForObstructingObject : MonoBehaviour {

    private Camera myCamera;

    private void Awake () {
        myCamera = camera;
    }
	private void Update () {
		RaycastHit info;
		if(Physics.Raycast (myCamera.ScreenPointToRay (transform.position), out info)) {
			if(info.transform.tag == "TheWantedTag") {
				info.transform.GetComponent<MyClassThatNeedsToGoTransparent>().isObstructingPlayer = true;
			}
		}
	}
}

The first class needs to be attached to the gameObject’s you want to go transparent, and the second one to the camera that does the check

The simplest thing would be to save the material for the object in a hash table and then set it back when it has to turn opaque.

Another approach would be to always use a transparent material and just tint its opaqueness with the color setting on the shader.

I wouldn’t recommend the latter though only because transparent shaders generally have sort issues and arent ideal for everyday usage.

Edit: Oh, , or are you asking how to determine when the ray isn’t hitting the object?

I do something something like this in my world builder. What I do is keep a list of all the objects I have set transparent. When the view angle moves, I set them all opaque and clear the lat, then generate a new one. ONLY do it when the camera has moved though, or its going to get pretty expensive.

In my case, my world is actually made up of cubic areas and I change entire cubes at a time which cuts significantly down on the processing.