Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect OnTriggerExit when disabling gameobject

I am facing a very simple problem about Triggers, but I don't see any way to solve it. I just want the OnTriggerExit function to be called when an object inside the trigger gets disabled.

Here is the way to reproduce the problem in an empty scene :

  1. Create a cube at (0,0,0) with a collider as trigger and the very simple following script :

    public class OnTriggerExitTest : MonoBehaviour
    {
        private void OnTriggerExit( Collider other )
        {
            Debug.Log( "Exiting : " + other.name );
        }
        private void OnTriggerEnter( Collider other )
        {
            Debug.Log( "Entering : " + other.name );
        }
    }
    
  2. Create a sphere at (0,0,0) with a Sphere collider and a Rigidbody which does not use Gravity

  3. Move the sphere out of the box, OnTriggerExit gets called

  4. Move the sphere back to (0,0,0), OnTriggerEnter gets called

  5. Disable the sphere, OnTriggerExit is not called

  6. Enable back the sphere, OnTriggerEnter is called

OnTriggerExitTest

Obviously, I want OnTriggerExit to get called when I disable my sphere. Do you know any solution ?

I am using Unity 5.4.1f

I could use events in the OnDisable function of my sphere of course, but it's not very clean. I simply do not understand why OnTriggerExit is not called but OnTriggerEnter is.

like image 401
Hellium Avatar asked Oct 30 '22 13:10

Hellium


1 Answers

There technically is no reason why Unity could not call OnTriggerExit in your scenario. A likely reason would be however that the "other" Collider is null given that is has been destroyed and would muck up a lot of situations if not handled.

However, you could work around it by using OnTriggerStay instead. It should be called every frame, and the first time it isn't called in your scenario that could mean the other collider got disabled.

like image 73
Bart Avatar answered Nov 23 '22 00:11

Bart