- Home /
How to register if my Raycast hits nothing(Solved)
Sorry if I word this incorrectly, but how do I register if a raycast hit returns null ?
At the moment I'm simply using a crude method of having an invisible wall behind the player (lowerWall) and having the raycast register that if it hits nothing else.
if(Physics.Raycast(shootingRay, out hit, attackDistance))
{
if(hit.collider.tag == "LowerWall")
{
Debug.Log("Searching");
}
else
if(hit.collider.tag == "ShieldCube")
{
Debug.Log("Blocked");
canFire = false;
}
else
if(hit.collider.tag == "Enemy")
{
canFire = true;
InvaderFireWeapon();
}
if(hit.collider.tag == "Player")
{
canFire = true;
InvaderFireWeapon();
}
}
Is there a way programmatically to check if a raycast doesn't actually hit anything
I tried -
if(hit.collider == null)
{
Debug.Log("Searching");
}
This didn't throw up any errors, but it didn't actually do anything either.
Any help greatly appreciated.
???
Answer by sumeeton · Mar 29, 2015 at 06:27 AM
Yes. If the raycast doesn't hit any collider, it returns false.
So, do it in the else statment. Simple!
if(Physics.Raycast(shootingRay, out hit, attackDistance))
{
// executes if hits a collider
}
else
{
// executes if it doesnt hit any collider
}
Sorry for late reply. Anyway.. works fine now, many thanks
:)
Answer by pietrovismara · Dec 03, 2016 at 09:39 AM
If no collider is hit, hit.collider will be null, so you can also check for it this way:
if (hit.collider == null)
{
}
First answer that actually considers the real problem. I was calling it from another script so I needed to check hit and the popular obvious answer was not a solution for me.
Your answer
Follow this Question
Related Questions
Finding when a Ray isn't hitting anything? 1 Answer
Hit distance Change light range 1 Answer
How to hit two object with one raycast? 2 Answers
Need help with Third person shooter 0 Answers
Help Playing "Sound Clip" on RayCastHit? (RayCast help?) 2 Answers