Search Unity

  1. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

OnCollisionExit not working when GameObject vanishes

Discussion in 'Scripting' started by Kinkku2, Aug 27, 2015.

  1. Kinkku2

    Kinkku2

    Joined:
    Sep 29, 2014
    Posts:
    106
    Hey! So I'm pushing a GameObject into another with a Rigidbody2D+collider. I have a OnCollisionExit2D on the Rigidbody object. I ran into problem where OnCollisionExit2D is not working when a GameObject gets disabled. The code doesn't register the GameObject vanishing as an exiting collision for some reason. Is there any way around this? Thank you.
     
  2. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    A gameobject needs to be active in order for it to interact with the physics engine, so disabling/destroying a gameobject means it will not called any OnTriggerExit/OnCollsionExit functions.

    There is are OnDestroy() and OnDisable() functions which allow you to add in some logic just before a gameobject is destroyed/disabled. You can use them to manually handle whatever logic you need to.
     
  3. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,250
    A solution I used was to translate the object far out of the game world and wait for one physics frame (which causes OnCollisionExit to fire), then destroy the object.

    --Eric
     
  4. Kinkku2

    Kinkku2

    Joined:
    Sep 29, 2014
    Posts:
    106
    Thanks a lot for the tips and sorry for the late reply! I'll have to try both in a few days.
     
unityunity