- Home /
How do I destroy a bullet when it hits something?
So I am making a space shooter game and I have an issue with the bullets, which is that when they hit an enemy the bullets will just keep going. I want to have it so when the bullets hit an enemy the bullets will be destroyed.
Answer by tormentoarmagedoom · Mar 04, 2020 at 07:05 PM
Hello.
You really doesnt need to use layermasks.
Just need to check which collider activated the function. Kishotta uses layermasks, but can check for the obkject tag or the object name or anything that fits in your project.
private void OnCollisionEnter (Collision collision) {
if (collision.gameObject.tag == "Something")
{
Destroy (gameObject);
}
or
private void OnCollisionEnter (Collision collision) {
if (collision.gameObject.name.Contains ("something")
{
Destroy (gameObject);
}
or anything. For example something "maybe useless" but correct, check for the value of a bool variable in a script attached to its parent. (Is just an example to show you you can check for anything)
private void OnCollisionEnter (Collision collision) {
if (collision.gameObject.parent.GetCoponent<SomeScript>().someBoolVariable == true)
{
Destroy (gameObject);
}
And using "this." here is unnecessary. this script should be attached to the bullet object, Because variable "gameObject" (not GameObject) always refear to the object that contains the script.
Answer by Kishotta · Mar 04, 2020 at 05:11 PM
You could attach something like the following to your bullet prefab. You may need to tweak it if you're using 2D colliders. Untested code, but should be close enough.
[RequireComponent (typeof (Collider))]
[RequireComponent (typeof (RigidBody))] // Cant remember if Rigidbody is required
public class DestroyOnCollision : MonoBehaviour {
public LayerMask CollisionMask;
private void OnCollisionEnter (Collision collision) {
// if collided object's layer is in layermask
if (LayerMask == (LayerMask | (1 << collision.gameObject.layer))) {
Destroy (this.gameObject);
}
}
}
I am getting this error message "error CSO119: 'Layer$$anonymous$$ask' is a type, which is not valid in the given context".
Hello @$$anonymous$$ishotta
When helping people, try to evaluate the "level" of the person. If he is asking for how to destroy something, its clear is just starting with Unity, so try to give more simple and easy solution. :D
Your answer
![](https://koobas.hobune.stream/wayback/20220612224359im_/https://answers.unity.com/themes/thub/images/avi.jpg)