How to find out if raycast dont hit anything

Hi everyone.i am creating a minecraft like game and atm i am about to create the build system. now i need to find out when the mouse/hit point(middle of screen) over an object then its have to make the block yellow and that work :slight_smile: but when the mouse/middle leave the block then the block keep being yellow :frowning: how can i make it white again?
plz help :slight_smile: thanks

Regards

Heres my code:

	Ray ray = Camera.main.ViewportPointToRay(new Vector3(.5f, .5f, 0));
	RaycastHit hit;


		if(Physics.Raycast(ray, out hit, 10)) {
		if(hit.transform.tag == "BlockOuter") {
			hit.transform.gameObject.renderer.material.color = Color.yellow;
		} else {
			hit.transform.gameObject.renderer.material.color = Color.white;
			
		}

This should work. Also unless you are working on a very small project, you will run into performance issues if you are using colliders for the edges of blocks. Or even β€œreal” blocks at all. You should read up on voxels. I know a great getting started tutorial on voxels, Ill find the link if you want it.

Ray ray = Camera.main.ViewportPointToRay(new Vector3(.5f, .5f, 0));
RaycastHit hit;
Transform lastHitTransform;
     
     
if(Physics.Raycast(ray, out hit, 10)) {
    //code in here run only if something is hit
        lasHitTransform = hit.transform;

         if(hit.transform.tag == "BlockOuter") {
             hit.transform.renderer.material.color = Color.yellow;
         } else {
            //This runs if something other than the tag BlockOuter is hit
             hit.transform.renderer.material.color = Color.white;             
         }
} else {
    //runs if nothing is hit
    lastHit.renderer.material.color = Color.white;
}

Edit: Corrected the code, since there is no hit information if you don’t hit anything as pointed out by Bunny83

Also here is the link to the voxel tutorial that really like Unity Voxel Tutorial Part 1: Generating meshes from code | GAME NETBOOK GRATIS