Destroying bullets after a certain amount of time
Hi,
I've been working on a shooting mechanic and the firing and everything is working fine. However, i don't know how to make it so that the bullets destroy after a certain amount of time. I've tried various methods but none seem to work. I want it so that I can still fire bullets after it has already destroyed some of the already fired ones. Any idea on how I might do that?
pragma strict
var bullet : Rigidbody; var bulletSpeed : int = 1;
function Start () {
}
function Update () {
if (Input.GetMouseButtonDown(0))
{
//Debug.Log ("Left click detected");
bullet = Instantiate (bullet, this.transform.position, Quaternion.identity);
bullet.AddRelativeForce(Camera.main.transform.forward * bulletSpeed);
}
}
Answer by Jessespike · Sep 30, 2015 at 04:33 PM
There are many ways. The simplest way is probably with GameObject.Destroy(), the 2nd parameter is a time delay before it destroys the object.
Destroy(bullet, 5f); // Destroy bullet object after 5 seconds
Not sure what you mean by "still fire bullets after it has already destroyed some of the already fired ones". If you're using a pooling system or a bullet manager class, you can make a coroutine to tell the bullet to reset. Something like:
IEnumerator DeactivateBullet(float delay) {
yield return new WaitForSeconds(delay);
// TODO: Tell the bullet manager or pooling system to reset this bullet
}
Your answer
Follow this Question
Related Questions
Resetting scene time after 13 seconds 1 Answer
I make a timing score script in unity 2D, how i make high score of time?? Script is as follow: 1 Answer
Add x amount in t seconds? 2 Answers
Get position of object that uses Perlin Noise X distance/time back/offset? 0 Answers
Change scene after event (time or clicking on object) 0 Answers