How do i find out when a raycast STOPS hitting something?

void Update () {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100))
{
if(hit.collider.tag == “cube”)
{
hit.collider.gameObject.GetComponent()._selected = true;

			}
		
			}
		
	}

so. I’ve got this code, which at the moment sets the Boolean value of _selected to true when a raycast hits the cube, it then changes the material of the cube, this works perfectly, what I want to do however, is find out when the raycast STOPS hitting the cube, so that the _selected variable can be set to false, thus restoring the original material.

void Update () {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100))
{
if(hit.collider.tag == “cube”)
{
hit.collider.gameObject.GetComponent()._selected = true;
GameObject temporaryObject = hit.collider.gameObject;
}
else if(temporaryObject != null)
temporaryObject.GetComponent()._selected = false;
}
}

This should work.

EDIT: On second thought, you should declare the temporaryObject somewhere up in your variables. Declaring it in the code like I just did will probably get you an error. Other than that, it should still work.

Cache the gameobject that is hit so that you can unset it.

private cubes cube;
if (Physics.Raycast(ray, out hit, 100) && hit.collider.tag == "cube")
{
    cube = hit.collider.gameObject.GetComponent<cubez>();
     cube._selected = true;
}
else if (cube != null)
{
    cube._selected = false;
    cube = null;
}