Trying to get bullet to collide and be destoryed

Hi ever one, I have a perfab called bullet which is basically a cube with two scripts attached to it.I got the bullet to spawn and to move forward, but I want it to hit something now and then disappear i.e destroy it, or do damage to another player. I really don’t know how to destroy the bullet upon impact with an object.

Thanks for any help with this here what I have so far

This spawns the bullet in from of the gun

using UnityEngine;
using System.Collections;

public class Bullet : MonoBehaviour {
	
	public Transform myBullet;//bullet prefab
	public Transform shotSpot;//shooting location

	// Use this for initialization
	
	
	// Update is called once per frame
	void Update () {
		if(Input.GetMouseButton(0))
		{
			Instantiate(myBullet,shotSpot.position,shotSpot.rotation);
		}
	}
	
	void OnCollisionEnter(Collision collision) {
	
		Debug.Log("Bullet hit");
		Destroy(myBullet);
	}
}

This one sends the bullet on its merry way

using UnityEngine;
using System.Collections;

public class BulletMovemnt : MonoBehaviour {

		public float bulletSpeed = 50;
	
	// Update is called once per frame
	void Update () {
		this.transform.position += this.transform.forward * bulletSpeed * Time.deltaTime;

	}
}

1 Answer

1

Take your collision function from the first script (remove it actually) and place it in the second script.

Now you may want to perform a check on what is hit by the projectile, you would do like this:

void OnCollisionEnter(Collision collision) {
   if(hit.gameObject.tag == "ObjectTag"){
      Debug.Log("I hit "+ collision.gameObject.name);
   }
   Destroy(myBullet);
}

Note that the destroy method is outside the if as you may want to destroy your bullet whatever it is hitting.

Ah thanks just put it in the wrong script