Hello!
The concrete case:
I have multiple game objects with convex mesh colliders and rigid bodies that are not moving.
Those are being instantiated over and over again next to each other.
The goal:
I am using the convex mesh colliders and the rigid bodies to check if there is space for the game object after instantiation.
The idea is that when a collision occurs - then there is no space and the game object should be destroyed. If not - then the game object remains.
The problem:
OnCollisionEnter is called even when the colliders are not touching, but are somewhat close to each other.
Check this image.
The execution:
I attach a script on the game objects with the colliders that is to detect collisions.
public class RoomCollider : MonoBehaviour {
public bool IsSpace { get; private set; } = true;
void Start()
{
IsSpace = true;
}
void OnCollisionEnter(Collision collision)
{
IsSpace = false;
}
}
An object is instantiated, the convex mesh colliders and the rigid body are added.
// A collider is instantiated based on a game object with multiple mesh colliders.
GameObject generationCollider = Instantiate(collider, room.transform);
// It is then scaled down a little.
float scaleDown = 0.95f;
generationCollider.transform.localScale *= scaleDown;
// A rigid body is then added.
Rigidbody rigidbody = room.AddComponent<Rigidbody>();
rigidbody.useGravity = false;
rigidbody.constraints = RigidbodyConstraints.FreezeAll;
rigidbody.useGravity = false;
// The mesh colliders are marked convex.
MeshCollider[] generationMeshColliders = generationCollider.GetComponentsInChildren<MeshCollider>();
foreach (MeshCollider meshCollider in generationMeshColliders)
meshCollider.convex = true;
The script waits for the FixedUpdate execution and then checks if a collision has occurred trough the “IsSpace” property.
What I have tried (and found on the forums):
Potential cause: Usually small scaled objects produce such behaviour
My case: My objects are scaled upwards and not downwards, but I played with scales and this shouldn’t be the case.
Potential cause: Unity predicts collision based on movement.
My case: My objects don’t move.