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?
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