Unity – Testing Collision on Instantiation for HFFWS

September 17, 2019

General Testing

HFFWS

Rigidbody Collision on Instantiation

Since having the system place objects itself is an eventual goal of my project, I wanted to see if rigid body gameobjects with colliders would collide immediately with each other if one was instantiated within the bounds of the other. I also wanted to check with collision checks would work best (or at all) for this, between OnEnter, OnExit, Stay, or anything else I could find.

To test this, I placed a cube (with collider and rigid body component) in the virtual space in the editor, and an empty gameobject that would be the TestSpawner at the same transform location. The TestSpawner simply instantiated an input gameobject at Start. This object was a simple sphere that had a collider and rigid body component. I think created a CollisionDetector script that I placed on both of these objects. This just had methods for OnCollisionEnter, OnCollisionExit, and OnCollisionStay to return a debug.log stating the name of the object itself and what it was colliding with, with information on which method it used to detect this collision.

The test did work as expected. They both immediately called OnCollisionEnter detecting each other, then had many OnCollisionStay calls as they stayed collided/near each other. Since the objects cannot occupy the same space, they did displace each other, which will be something I will have to monitor in the future. I am not sure if this will be an issue, but depending on how precisely objects need to be located in their original positions, this could cause some issues. I may need something that can detect an impending collision and stop an instantiation process before actually displacing the existing object.