- Home /
RaycastHit if/else Problem (bug?)
So, I'm using Raycasts to detect whether something is in front of me. And I have this simple code:
if (Physics.Raycast (playerCam.transform.position, playerCam.transform.forward, out hit)) {
print ("good");
} else {
print ("bad");
}
As I understand it, the console will print "good" when colliding with something, and "bad" when not colliding. However, when I view it in the console:
When colliding: good bad good bad (alternating)
When not collding: bad bad bad bad (solid)
I'm using the latest version of Unity. Is this a fix for this so that when colliding, it returns in a solid manner?
$$anonymous$$aybe print what its hitting ins$$anonymous$$d? You havent specified a max distance.
$$anonymous$$aybe you have attached this code to more than one object? Where and when is this code actually executing? You haven't really provided much context. Use proper log statements like:
if (Physics.Raycast (playerCam.transform.position, playerCam.transform.forward, out hit))
{
Debug.Log("Object " + gameObject.name + " casted a ray and hit " + hit.collider.gameObject.name+ " at a distance of " + hit.distance, gameObject);
}
else
{
Debug.Log("Object " + gameObject.name + " casted a ray but doesn't hit anything", gameObject);
}
Note the second parameter. It provides a context object for the log entry. When you click the log in the console Unity will ping that object in the hierarchy which might help to figure out which object actually casted that ray. If you still have problems you can also print out the position and the direction of the raycast.