- Home /
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[i] == null)
{
switch(_tag)
{
case "weapons_knife":
inventory[i] = inventoryObject.AddComponent<Knife>();
break;
case "weapons_sword":
inventory[i] = inventoryObject.AddComponent<Sword>();
break;
case "weapons_stapler":
inventory[i] = inventoryObject.AddComponent<Stapler>();
break;
case "items_staple":
inventory[i] = inventoryObject.AddComponent<Staple>();
break;
default:
Debug.Log("oops");
break;
}
Destroy(other.gameObject);
break;
}
}
}
}
Answer by DZeb · Apr 18, 2019 at 10:05 PM
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.
Your answer
![](https://koobas.hobune.stream/wayback/20220612195730im_/https://answers.unity.com/themes/thub/images/avi.jpg)