- Home /
How to not trigger OnTriggerExit2D when an Object is destroyed?
I have a Player object but the items I'm picking up are triggering the OnTriggerExit2D of my player script whether it gets destroyed or disabled.
This characteristic is very annoying and I believe that if an object is destroyed, it shouldn't trigger OnTriggerExit. I've tested this on 3D OnTriggers and it doesn't do this. How do I disable this?
not sure but you can call after
void OnTrigerEnter2D() {
}
void OnTriggerExit2D() { //trigger exit
}
void OnDestroy() { //all action performed and last this one called onDestroy you can use courutione }
sure it is work use courutine
Answer by unity_21erushbrook · Jul 21, 2019 at 04:52 AM
Just check if isActiveAndEnabled is true on the object that's exiting. If it is, just return out of the function.
Answer by MANA3DGames · Jul 21, 2019 at 09:01 AM
Neither OnTriggerExit nor OnTriggerExit2D should be triggered by a destroyed object.
Are you sure that the picked item is the one who triggers the OnTriggerExit2D of the player? Are you destroying the picked item immediately? or after few seconds? Destroy( itemGameObject, DestroyAfterSomeSeconds );
if you are destroying the item immediately before it leaves the trigger area of the player then this should not happen.
Here is a few steps could help you debugging this issue:
In your Player script add the following
private void OnTriggerEnter2D(Collider2D collision)
{
if ( collision.tag == "Item" ) // replace it with your item tag
{
Debug.Log( "I'll pick up this item so you can destroy it NOW!" );
Destroy( collision.gameObject );
}
}
private void OnTriggerExit2D( Collider2D collision )
{
if ( collision.tag == "Item" )
{
// If everything is working right then you should not see this line.
Debug.Log( "Yes this is the picked item: " + collision.gameObject.name );
}
}
In your Item script add the following
private void OnDestroy()
{
Debug.Log( "I was destroyed by the player!" );
}
Ideally, you should see the following lines in your console (in this exact order):
"I'll pick up this item so you can destroy it NOW!"
"I was destroyed by the player!"
Otherwise something else is calling the Player OnTriggerEnter2D
Your answer
