Detect OnTriggerExit when disabling gameobject
Asked Answered
A

1

7

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.

Aramenta answered 18/1, 2017 at 10:16 Comment(0)
A
2

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.

Acrogen answered 18/1, 2017 at 11:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.