Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

OnCollisionEnter2D is not working although trying many different things

I have this as a function:

    public void OnCollisionEnter2D(Collider2D collision)
{
    if (collision.gameObject.name == "ColliderLeft")
    {
        Debug.Log("Left");
        //transform.position(-9.5f, transform.position.y);
    }
}

my collider, start and update function, still its not working.

    public Collider2D collider;

void Start()
{
    collider = GetComponent<Collider2D>();
}

void Update()
{
    OnCollisionEnter2D(collider);
}

my script error is Script error: OnCollisionEnter2D
This message parameter has to be of type: Collision2D
The message will be ignored.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Several things to note here:
collider and collision are not the same things.
Collider2D represents a 2D collider that you have attached to a gameobject (for example a hitbox).

A Collision2D is an event that happens when Collider2D comes in contact with another Collider2D.

Note the difference: Collider != Collision

When a collision happens, Unity sends a message OnCollisionEnter2D to both gameObjects that are involved in a collision.
Do not try to call it in the Update because you don’t have the collision to provide. Again, Collision is not a Collider

Change

public Collider2D collider;

void Start()
{
    collider = GetComponent<Collider2D>(); // this is ok
}

void Update()
{

}

private void OnCollisionEnter2D(Collision2D collision) // changed Collider2D to Collision2D
{
    if (collision.gameObject.name == "ColliderLeft")
    {
        Debug.Log("Left");
        //transform.position(-9.5f, transform.position.y);
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading