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.

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.

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);
		}			
	}
}