- Home /
OnCollisionEnter2D is not detecting collisions.
I have a game object 'Crowd' that is instantiated in the scene multiple times. Each time it instantiates, it creates a clone called 'Crowd(Clone)' in the scene. I wish to destroy this game object each time it moves out of the scene bounds. For this, I created a blank game object and placed it outside the area where the camera cant see and I put a script on this game object to Destroy each copy of the instantiated object if it collides with this destroyer. The following is the script that I have attached to this destroyer.
using UnityEngine;
using System.Collections;
public class SpawnKill : MonoBehaviour {
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.name == "Crowd(Clone)")
{
Debug.Log("Hit");
Destroy(collision.gameObject);
}
}
}
Both the game objects, 'Crowd' as well as the destroyer, have a Box Collider 2D components. I tried turning on the 'Is Trigger' checkbox, as well as rename the collision.gameObject.name from 'Crowd(Clone)' to 'Crowd' but it just wouldnt detect.
For some reason, the collisions are just not detecting and I don't know why. I'm using the 2D interface in Unity.
Any ideas anyone ?
No. I don't have RigidBody2D attached to either the game object nor the destroyer, the reason being, I'm working on a Top Down concept and RigidBody tends to add gravity and mass to it and makes it go into a freefall, which I dont quite require.
I would suggest using Tag rather than name...
I am "newer" to unity so I am not that experienced.
Hope this helps :D
I already tried to assign a tag to the instantiated game objects and used that tag on the destroyer script but it yet does not detect the collisions oddly :(
Have you tried using OnTriggerEnter ins$$anonymous$$d? $$anonymous$$ake sure the Is Trigger checkbox is on when you use this.
Answer by coolbird22 · Apr 04, 2014 at 08:03 AM
Adding a RigidBody2D was making the game object fall down. I just reduced the Mass to 0.0001, Angular Drag and Gravity Scale to 0 and it started working like I wanted it to. Awesome !!
Answer by haim96 · Apr 04, 2014 at 08:14 AM
make sure you using 2d colliders also, you can use 2d rigidbody and disable gravity.
Your answer
Follow this Question
Related Questions
Detect 2 colliders by trigger 1 Answer
Collision flag entering a tagged object's collider 2 Answers
Something wrong with destroying script 0 Answers