OnCollisionEnter2D not working properly !

So i’ve been working on my latest 2D game , and I’ve done it that if a rocket hits my player (which is a planet) , both of them blow up… BUT i’m trying to make it that two rockets blow up if they hit eachother as well , but that’s not working , only if it’s a player vs a rocket !

The both rockets are the SAME , which means same tags , same kind of collider (Polygon 2D) , same components , etc… i tried to change the tag or add an another 2D Collider , but none of that worked :confused:

Here’s my script :

    void OnCollisionEnter2D(Collision2D other)
    {
        if (other.gameObject.tag == "Player") {
            ((MonoBehaviour)gameObject.GetComponent ("FireBase")).enabled = true; //Blowing up effect
            KillPlayer ();
            StopRocket = true;
            StopJoystick = true;
           
            gameObject.GetComponentInParent<SpriteRenderer> ().enabled = false;
        }
   
        if (other.gameObject.tag == "Rocket") {
            Debug.LogError("+1 Point");
            ((MonoBehaviour)gameObject.GetComponent ("FireBase")).enabled = true; //Blowing up effect

        }
    }

Any help is very appreciated !!
Thanks :slight_smile:

So which part is not working? Does the OnCollisionEnter2D get called when it’s a Rocket-Rocket collision? Does your debug statement get called?

By the way, you don’t need to write “gameObject.GetComponent”, just “GetComponent” works fine.

Also, you can use the same syntax for the GetComponent() as for GetComponent().

You may need a box collider :wink:

Bro i tried.
And logically it should work on any other collider as well , it’s a collider after all !

The Rocket-Rocket Part is not working , this script is attached to the rockets , and no the debug statement doesnt get called :confused:

Um i think i do need to write gameObject.GetComponent here Because it has the (MonoBehavior) before it. in other cases i know you can write GetComponent<> alone :slight_smile: .

p.s : i’m writing (MonoBehavior) before the GetComponents because it’s not finding the components i want if i write it regularly , so this is an another way , and worked !

Do the rockets have rigid bodies attached?

1 Like

No… only the player has one

I just tried adding rigidbodies to the rockets and it WORKED!!!
Thanks a lot man really appreciate it!

No problem. I’m not 100% certain but I’m fairly sure that at least one object in a collision/trigger event has to have a rigid body, even if it iskinematic.

The problem is that a collider with a Rigidbody2D is a static collider and should not be moved. Static colliders don’t contact each other. When you add a Rigidbody2D then it becomes a Dynamic/Kinematic body.

If you look at the 2D experimental preview reference guide, I explain the body-type in more detail: http://forum.unity3d.com/threads/2d-experimental-preview-release-1.407658/

2 Likes

Thanks a lot !
I got it :smile: