- Home /
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;
}
}
Answer by fafase · Mar 27, 2013 at 02:43 PM
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.
Your answer
![](https://koobas.hobune.stream/wayback/20220613095211im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
using Contains(gameObject) to find and destroy a gameObject from a list 2 Answers
How to Play 3D Sound and Keep Script on Multiple Prefabs after Destroying a gameObject? 0 Answers
Trouble with destroying an instantiated prefab 2 Answers
Check if object is destroyed on level load, if so instantiate prefab? 1 Answer