- Home /
How could i make it so that my bullets destroy after x amount of seconds?
I want to make it so that after i shoot in my shooting script the bullet is destroyed after x amount of time but i cant figure out how nothing is working ive tried call destroy in and out of the function and it wont work please help!?
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Shooting : MonoBehaviour {
public Rigidbody2D bullet;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetButtonDown("Fire1"))
{
Rigidbody2D clone;
clone = Instantiate(bullet, transform.position, transform.rotation);
clone.velocity = transform.TransformDirection(Vector2.up * 15);
DestroyObject(clone, 1f);
}
}
}
Answer by Bunny83 · Nov 11, 2017 at 01:45 AM
Just do:
void Update()
{
if (Input.GetButtonDown("Fire1"))
{
Rigidbody2D clone;
clone = Instantiate(bullet, transform.position, transform.rotation);
clone.velocity = transform.TransformDirection(Vector2.up * 15);
Destroy(clone.gameObject, 1f);
}
}
Note the important thing is when you do Destroy(clone, 1f)
instead of Destroy(clone.gameObject, 1f);
you only destroy the Rigidbody2D component but not the gameobject it's attached to.
Answer by ShadyProductions · Nov 11, 2017 at 01:40 AM
Add a script to the bullet prefab with a timer that removes it after amount of seconds when it becomes instantiated.
public float TimeLeft = 5;
void Update() {
TimeLeft -= Time.deltaTime;
if ( TimeLeft < 0 )
{
Destroy(this);
}
}