- Home /
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 :) but when the mouse/middle leave the block then the block keep being yellow :( how can i make it white again? plz help :) 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;
}
@mh92: No you can not. If the Raycase doesn't hit anything the RaycastHit struct isn't filled with anything. That's why Raycast returns a boolean which tells you if it hits something. Only if it returns true the content of the RaycastHit struct has a meaning.
Answer by Linus · Dec 09, 2014 at 01:10 AM
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 http://netbook-game.blogspot.no/2013/08/unity-voxel-tutorial-part-1-generating.html
@Linus: Well, it makes not much sense to use hit inside the else branch of your Raycast since it won't contain "an object" you "don't hit" ^^
You should save the last hit object in a variable and if you hit a new block or nothing revert the color of the saved object.
oh snap that is true. Ill see to update answer. Guess I did not really read that line, for some reason I assumed he changed color of an ai$$anonymous$$g marker.