Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Collision detection

Discussion in '2D' started by steg90, Jan 21, 2019.

  1. steg90

    steg90

    Joined:
    Jan 26, 2016
    Posts:
    93
    Hi,

    Is there a better way of doing the below:

    Code (CSharp):
    1.  private void OnCollisionEnter2D(Collision2D collision)
    2.     {
    3.         if (collision.gameObject.name != "Player")
    4.         {
    5.             if (!collision.gameObject.tag.Contains("bull"))
    6.             {
    7.                 Destroy(gameObject);
    8.             }
    9.         }
    10.     }
    What I'm trying to avoid here is, if the collision is the player then don't destroy or if the collision is one of the players bullets being fired then again don't destroy.

    Thanks
     
  2. hlw

    hlw

    Joined:
    Aug 12, 2017
    Posts:
    250
    Well, that would mean that any other collision would destroy the gameobject. Depending on your project, it could work, but i would do somehow the opposite. Put a tag on the things that should destroy your game object, and just ask:
    Code (CSharp):
    1.  private void OnCollisionEnter2D(Collision2D collision)
    2.     {
    3.         if (collision.gameObject.tag == "Destroyer")
    4.         {
    5.                 Destroy(gameObject);
    6.         }
    7.     }
    You could also set Physics2D.IgnoreLayerCollision

    Code (CSharp):
    1.         Physics2D.IgnoreLayerCollision(this.gameObject.layer, player.gameobject.layer, true);
    2.         Physics2D.IgnoreLayerCollision(this.gameObject.layer, bullet.gameobject.layer, true);
    Depends a lot on your actual game logic.
     
    steg90 likes this.
  3. steg90

    steg90

    Joined:
    Jan 26, 2016
    Posts:
    93
    Many thanks for this, much appreciated.