Reputation: 27
I have a script which I use multiple raycasts from one object to check if there is a specific layer mask is hit and I'm using for
loop between them and it works fine.
But the problem is: if one of the rays is hit boolean
will be true
and if "all" the rays are not hit, boolean
will be false
. But the problem is I don't know how to check that.
for (int i = 0; i < rays; i++)
{
Vector2 raysStart = raysStart.topLeft + Vector2.right * (raysSpacing * i);
RaycastHit2D hit = Physics2D.Raycast (raysStart, Vector2.up, 10, checkMask);
if (hit)
{
Debug.DrawLine (raysStart, raysStart + Vector2.up * 10, Color.red);
boolean= true;
}
else if (!hit)
{
Debug.DrawLine (raysStart, raysStart + Vector2.up * 10, Color.green);
boolean= false;
}
}
I also tried with else
without else if (!hit)
and it worked the same.
So there are 4 rays if one of the rays hit three other gives not hit so it always give me not hit accept.
If I hit the last ray in the loop any way as I seed if you can tell me how to make if one ray from the 4 rays is hit the boolean
becomes true
and if all the 4 rays not hit it becomes false
.
Upvotes: 1
Views: 1424
Reputation: 27
Crusha K. Rool have answered correct answer and there is another answer I have found
boolean= false;
for (int i = 0; i < rays; i++)
{
Vector2 raysStart = raysStart.topLeft + Vector2.right * (raysSpacing * i);
RaycastHit2D hit = Physics2D.Raycast (raysStart, Vector2.up, 10, checkMask);
if (hit)
{
Debug.DrawLine (raysStart, raysStart + Vector2.up * 10, Color.red);
boolean= true;
}
else if (!hit)
{
Debug.DrawLine (raysStart, raysStart + Vector2.up * 10, Color.green);
}
}
The Idea here is that the Boolean default is false and also it update every time you call the function so you check if hit the Boolean will be true and if not hit you don't need to check its automatic return to false if you Update the function
Upvotes: 0
Reputation: 1502
According to the documentation, hit.collider
will be null
if nothing was hit.
bool anyHit = false;
for (int i = 0; i < rays; i++)
{
Vector2 raysStart = raysStart.topLeft + Vector2.right * (raysSpacing * i);
RaycastHit2D hit = Physics2D.Raycast (raysStart, Vector2.up, 10, checkMask);
if (hit.collider != null)
{
anyHit = true;
break; // Don't need to check the rest after we found one hit.
}
}
Upvotes: 2