Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
412 views
in Technique[技术] by (71.8m points)

collision - How to check which objects collide

i have an example : player object, obstacle_1 object and obstacle_2 object. How do I check which one player collides with? I mean I want to do script_1 for colliding player with obstacle_1 and do script_2 when player collides with obstacle_2. Example:

private void OnTriggerEnter2D(Collider2D collision)
{
    //script 1 when this object(player) collides with obstacle_1;

    //script 2 when this object(player) collides with obstacle_2;
}
question from:https://stackoverflow.com/questions/65871600/how-to-check-which-objects-collide

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It seems like you're asking how to differentiate between objects. There are many ways of doing so, and it's hard to say which will work best for you since you didn't give a lot of context. Here are some ideas:

  1. One of the simplest ways would be comparing the object's names:

private void OnTriggerEnter2D(Collider2D collision)
{
    if(collision.gameObject.name == "Obstacle_1"){
      //React to obstacle 1
    }
    else if (collision.gameObject.name == "Obstacle_2"){
      //React to obstacle 2
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...