In my scene I have a Standard Assets’ First Person Controller (with a kinematic Rigidbody and a CharacterController component).
At a certain point, I spawn an arbitrary number of pick-up-able objects. These objects need to be affected by physics, and therefore have a (non-kinematic) Rigidbody and a physical BoxCollider. They also have a SphereCollider marked as Trigger that is significantly larger than their BoxCollider, and marks the zone the player has to enter to pick up the object.
In case it’s relevant, the objects’ Rigidbodies are restricted to only Y movement (rotation is free in all directions), and everything uses Discrete collision detection.
The problem I am facing is that the OnTriggerEnter method in the script attached to of these objects does not get called consistently when my character enters the SphereCollider. In fact it generally only gets called after I’ve bumped into the object several times with my character.
Now according to the table in the manual, OnTriggerEnter should be getting called in this case:
However it is not working properly.
I have tried a few alternatives, like:
- attaching the OnTriggerEnter script to the character instead of the objects
- putting one or both of the object’s colliders onto (distinct) child objects
- removing the SphereCollider entirely and only using the BoxCollider with the OnCollisionEnter method instead of OnTriggerEnter
The first two had the exact same result as the original setup, while the third didn’t work at all.
The solution I’m currently using is a raycasting in the character’s Update towards all pickup objects (which only have their BoxColliders, no trigger SphereColliders) in the scene to see if they’re close enough, and picking up those that get hit by the raycasts. This does work properly, but it seems like a very crude and inelegant solution, and with a massive performance hit in the case of a larger number of pickup objects (calling GameObject.FindGameObjectsByTag every frame, and raycasting towards all of them).
Why isn’t the original setup working, and is there a better way to approach this problem?
P.S. In the same scene I use a very similar setup with the tool rack (which spawns the tools when approached), except that it doesn’t have a Rigidbody component (as it is stationary and doesn’t need to be affected by physics). That one works without problems with a physical BoxCollider and a trigger SphereCollider.