RaycastHit not returning null when no collider is detected
Hi all, It's my first time here so pardon me if i did anything wrong.
I have a simple SphereCastAll that prints the object's name when hit, like in my example, it hits the terrain.
if the array is not null, it will also log "in not null", before printing the object's name.
However when it does not hit anything, it does not return null but does not print anything as well other than saying it is in the "in not null" loop. Any idea what might be the cause? Thank you Below is my code snippet
void Update()
{
CheckIsOnEdge();
}
void CheckIsOnEdge()
{
//RaycastHit hitInfo;
RaycastHit[] allHit = Physics.SphereCastAll(edgeTrackerTrans.position, 0.1f, transform.forward, 0.1f);
if(allHit != null)
{
print("in not null");
foreach(RaycastHit hit in allHit)
{
print(hit.collider.gameObject.name);
}
m_Animator.applyRootMotion = true;
}
else
{
print("nothing hit");
}
}
Answer by Bunny83 · Sep 03, 2020 at 01:04 AM
SphereCastAll will always return an array. It will never return null. If no colliders were hit, it just returns an empty array. So you should do something like this instead:
if(allHit.Length > 0)
{
foreach(RaycastHit hit in allHit)
{
print(hit.collider.gameObject.name);
}
m_Animator.applyRootMotion = true;
}
else
{
print("nothing hit");
}
Your answer
Follow this Question
Related Questions
SphereCast in standard Character Controller? 0 Answers
Avoid spherecast from shrinking over distance / find withing screenspace 0 Answers
How do I use a spherecast to spawn multiple target images at multiple objects? (script provided) 1 Answer
Get all world co-ords within x units of player 0 Answers
Physic SphereCast hits null 1 Answer