Collision not working
I want my player to get hit by an enemy missile, which spawns automatically. Both missile and player have rigidbodys and circular collider and are on the same layer, tags are set. This is the code I use: void OnCollisionEnter2D(Collision2D col) { if (col.gameObject.tag == "Stein") { playerhealth -= 10; Debug.Log("HIT"); Destroy(col.gameObject); } }
Even though the player get knocked back when the missile hits him, the collision is not detected. Any idea why it does not work and how I can fix it?
Add some more debug logs, to print the col.gameObject.name and gol.gameObject.tag, before any conditional statements. $$anonymous$$ake sure they are as expected. If this code is attached to the player, add some similar code to the missile, maybe it is hitting a collider attached to the player, but not the specific one that you think it will.
Adding the code to the missile works, thanks! But it only works when the missile is not a trigger. But I don't want the player to get knocked back by it, what can I do to achieve this?
I did not necessarily mean for you to leave the code on the missile, I meant for you to add it along with some Debug statements, in order to identify what each collider is hitting, and whether it is as expected. As Toby says, if you want to use triggers, you need to change the method used from OnCollision... to OnTrigger...
Answer by TobyKaos · May 02, 2016 at 09:24 AM
If you do not want to have force apply on Object when hit you must use OnTriggerEnter2D(Collider2D other) function instead of OnCollisionEnter2D
Be sure to have added RigidBody2D and and BoxCollider2D (or other Collider2D) on Character if you want to walk on a physic ground. Add only a BoxCollider2D( or other) on missile with the IsTrigger checked for it. No rigidbody2D on missile needed. On Missile script add OnTriggerEnter2D function.
If you want detection on character side script the add a child object on character with Collider 2D object and IsTrigger checked. In this case I think you also need a RigidBody2D on missile.
Your answer
Follow this Question
Related Questions
How to check if any/multiple 2D sprites neighbour/collide with eachother 0 Answers
Unable to stop animation upon collision (2d, animation, rigidbody) 0 Answers
How to check if a collider is Touching any other object 2 Answers
2D Collisions Not Working,2d Collision not working? 0 Answers
Unity Collider2D is causing the game object to disappear upon collision? 1 Answer