- Home /
OverlapBoxNonAlloc not working correctly when called multiple times in single frame
I have an editor script that locates spawn locations. I use OverlapBoxNonALlloc to determine if a location is free of obstacles. In about 5% of cases, the OverlapBoxNonAlloc does not detect that there is a collision with an existing object.. I have gone over this every which way, but I can't understand why this is failing.
The GetPlacement method will loop and test random locations until it finds one that does not overlap with an existing object, or the maximum attempts are exceeded. When successful, it places a temporary cube at that location.
In the youtube video, you can see that the majority of cubes are placed in non-overlapping locations. But a small number of them overlap other cubes.
Video showing issue: https://youtu.be/8KnzTn9Hb68
private bool GetPlacement(PoolDefinitionScriptableObject item, Bounds bounds)
{
Vector3 boxPosition = Vector3.zero;
var position = RandomPointInBounds(bounds);
// Ensure the spawn point is clear of any obstructing objects.
if (item._CheckForObstruction)
{
var attempt = 0;
var success = false;
while (attempt < item._PlacementAttempts)
{
boxPosition = position + Vector3.up * (item._Size.y * 0.5f + 0.2f);
// Check for collision
var overlapCount = Physics.OverlapBoxNonAlloc(boxPosition, item._Size * 0.5f, _ObstructionColliders, Quaternion.identity, item._ObstructionLayers, QueryTriggerInteraction.Ignore);
success = overlapCount == 0;
if (success)
{
break;
}
++attempt;
position = RandomPointInBounds(bounds);
}
// No valid position was found - return false.
if (!success)
{
return false;
}
}
// If the ground snap height is positive then the position should be located on the ground.
if (item._GroundSnapHeight > 0)
{
RaycastHit raycastHit;
if (Physics.Raycast(position + Vector3.up * item._GroundSnapHeight, -Vector3.up, out raycastHit, item._GroundSnapHeight + 0.2f, item._ObstructionLayers, QueryTriggerInteraction.Ignore))
{
position = raycastHit.point + Vector3.up * 0.01f;
}
}
CreateSpawnCube(position + (Vector3.up * (item._Size.y * 0.5f)), item._Size);
return true;
}
public static GameObject CreateSpawnCube(Vector3 location, Vector3 size)
{
var shape = GameObject.CreatePrimitive(PrimitiveType.Cube);
shape.transform.localScale = size;
shape.transform.position = location;
var material = (Material)Resources.Load("Red");
if (material == null)
{
Debug.LogError("No material resource found");
return null;
}
shape.GetComponent<Renderer>().material = material;
return shape;
}
[1]: https://youtu.be/8KnzTn9Hb68
Answer by Zaddo · Feb 08, 2021 at 09:50 AM
I found the solution here: https://forum.unity.com/threads/solved-strange-behavior-with-overlapbox.833299/
Credit to @Baste
Your answer