OnTriggerEnter2D() and OnTriggerExit2D() are calling twice.

Hi. I’m making an inventory system right now and all is going well, however the actual collection of items is not working. I think it’s because OnTriggerEnter2D is being called twice. I’ve also tried using Exit() and Stay() but I get the same outcome.

My script works like this:

  • When the player collides with an object…
  • You get the object’s details from a script contained within the prefab (this is so I can check for ammo in the magazine etc. at a later date)…
  • It checks whether there is space in the inventory…
  • If there is the item is destroyed in the world and added to the inventory.

But sometimes two items are being added to the inventory.

Here’s my code:

private void OnTriggerEnter2D(Collider2D other) 
{
    if (other.gameObject.tag == "item")
    {
        string _tag = other.gameObject.GetComponent<ItemIdentifier>().itemName;

        Debug.Log("picked up a " + _tag);
        for(int i = 0; i < inventory.Length; i++)
        {
            if(inventory *== null)*

{
switch(_tag)
{
case “weapons_knife”:
inventory = inventoryObject.AddComponent();
break;
case “weapons_sword”:
inventory = inventoryObject.AddComponent();
break;
case “weapons_stapler”:
inventory = inventoryObject.AddComponent();
break;
case “items_staple”:
inventory = inventoryObject.AddComponent();
break;
default:
Debug.Log(“oops”);
break;
}
Destroy(other.gameObject);
break;
}
}
}
}

I’ve read about this happening if both the player and the object colliders are marked as “isTrigger”. Also check if by any chance you have another collider in the children of said object.