- Home /
Solved
[SOLVED] Destroy instantiated object prefab on collision
Hi,
I want to shoot bullets and once they hit objects I want them (bullets) to get destroyed (and/or trigger some more events, for particle effects mostly)
So Im shooting my bullets with this script:
using UnityEngine;
public class Shoot : MonoBehaviour {
public float bulletLife = 1f;
public GameObject bulletPrefab;
void Update()
{
if (Input.GetButtonDown("Fire1")) {
GameObject bullet = SpawnBullet();
ShootBullet(bullet);
KillBullet(bullet);
}
}
GameObject SpawnBullet()
{
var bullet = (GameObject)Instantiate(
bulletPrefab,
transform.position,
transform.rotation);
return bullet;
}
void ShootBullet(GameObject bullet)
{
bullet.GetComponent<Rigidbody>().velocity = bullet.transform.forward * 6;
}
void KillBullet (GameObject bullet)
{
Destroy(bullet, bulletLife);
}
}
And Im using this script on a bullet prefab, hoping to destroy itself on collision:
using UnityEngine;
public class destroyOnCollision : MonoBehaviour {
void OnCollisionEnter(Collision collision)
{
Destroy(gameObject);
}
}
But unfortunately it does not work. It works well on any objects that collide with bullets, but the bullet prefabs do not destroy.
Maybe Instantiate() does not instantiate scripts components? Or they are not active or sth?
Answer by JJ_FX · Oct 10, 2018 at 05:30 PM
Omg... it actually works fine. I just didnt notice that I spawned my bullets too close to another collider. And my bullets were destroying too fast and I was getting weird readings in Debug.Log.
So actually its SOLVED :)