- Home /
OnTriggerEnter2D not working
So what i'm trying to do is make my Player (which has a Circle Collider 2D and a Rigidbody 2D) hit a coin (circle colider 2D + is trigger activated) and make the coin disappear.
But my player and coin are simply not doing anything, the player just goes over the coin.
I have verified the layer, sorting layer, order in layer, the coin tag and they're all ok. I also checked in the physics 2D in the Project Settings and the Coin layer and the Player layer are selected to collide. When i get the 'is trigger' off the coin, they do collide but that's not what i want, i need it to be a trigger.
The script i'm using on the player is:
void OnTriggerEnter2d(Collider2D collider)
{
if (gameObject.tag == "Coin")
{
Destroy(coin);
gm.Points += 1;
}
}
(Ignore the gm.Points += 1, that's a part of my score system, and i doubt it's part of the problem.)
What should i do about it?
Answer by Xpartano · Mar 01, 2018 at 08:54 AM
Well I think your main problem is that you're checking the tag of the current gameObject and not the object you're triggering. Your condition if (gameObject.tag == "Coin")
is checking if the object that actually contains this script has the tag "Coin".
I suppose the object that holds this script in your game is your Player object (maybe with the "Player" tag), so when you ask if (gameObject.tag == "Coin")
, it just won't run. I think what you really want is to use if (collider.tag == "Coin")
instead of if (gameObject.tag == "Coin")
.
Also check the spelling of your event. It should be OnTriggerEnter2D
Let me know if doing this simple change you get what you expected :)