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

How to destroy a object if it is in a specific layer on collision with an object? (Both rigidbody)

Discussion in 'Editor & General Support' started by VVieleDev, May 17, 2020.

  1. VVieleDev

    VVieleDev

    Joined:
    Aug 8, 2019
    Posts:
    1
    I am using Unity 2019.3.9, and I am getting a newer version now, but in my game, I have a gun that shoots bullets, the bullet is a rigidbody, how do I destroy a object on collision in a layer "Enemy"?

    Right now, I have a box on the layer "Enemy" and it's name is "Enemy". And I want it to dissapear (possibly with an effect) when the bullet hits it.

    (Note, the gun is a child of 'Main Camera' so you aim where you are looking, also it is a double pistol)
     
  2. dgoyette

    dgoyette

    Joined:
    Jul 1, 2016
    Posts:
    4,193
    Depends on how you're shooting, but the general idea is the same. Are you moving the bullet with physics? If so, you can put an OnCollisionEnter method on a script on the object, and test whether the object you collided with is on layer Enemy. (Alternately, you can put the bullet on its own layer, and adjust the Physics settings so that bullets only hit Enemy objects.) The problem with this approach is that if the bullet is moving very fast, it might pass through the enemy without triggering a hit.

    The alternative is raycasting from the barrel of the gun when firing the bullet, and immediately determine whether the gun is aimed directly at an enemy. You'd use Physics.Raycast, and test whether the object you hit is on layer Enemy. Those are the two basic approaches.