S
S
Shallmick2021-04-20 08:22:01
2D
Shallmick, 2021-04-20 08:22:01

How in Unity (2D) to make a reaction to the collision and separation of objects?

This is my code for the collision reaction, but I don’t know how to make the disconnect reaction.

public class Enemy : MonoBehaviour
{
    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag == "Player") {
            collision.gameObject.GetComponent<player>().RecountHp(-1);
            collision.gameObject.GetComponent<Rigidbody2D>().AddForce(transform.up * 14f, ForceMode2D.Impulse);
        }        
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
ReyGrau, 2021-04-20
@Alexander_020

OnCollisionExit2D all this is googled in a couple of minutes. And instead of checking the tag, it's better to check if there is any component on the object.

private void OnTriggerEnter2D(Collider2D other)
  {
    if(other.GetComponent<PlayerController>() != null)
    {
      ...
    }
  }

G
GavriKos, 2021-04-20
@GavriKos

Now, if you take and open the OnCollisionEnter2D manual and read it CAREFULLY, you can find the answer.
https://docs.unity3d.com/ScriptReference/MonoBehav...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question