Destroy instantiated Projectile after time
I'm writing a C# script to shoot. i also want to destroy the instanted Projectile after a time of 2 seconds but it does not work. here is my script:
using UnityEngine;
using System.Collections;
public class shoot : MonoBehaviour
{
public Rigidbody myShot;
private float speed = 20;
void Update()
{
if (Input.GetButtonDown("Fire1"))
{
Rigidbody instantiatedProjectile = Instantiate(myShot, transform.position, transform.rotation) as Rigidbody;
instantiatedProjectile.velocity = transform.TransformDirection(new Vector3(0, 0, speed));
Object.Destroy(instantiatedProjectile, 2.0f); // should destroy instantiated Projectile after 2s
}
}
}
can anyone halp me?
Try this ins$$anonymous$$d:
GameObject.Destroy( instantiatedProjectile.gameObject, 2f );
With your current code, I think what you're doing is destroying the Rigidbody component itself.
Answer by The_Magical_Muffins · Mar 26, 2017 at 05:48 PM
Put this script on the prefab that is being instantiated
function Start () {
yield WaitForSeconds(2); //Wait two seconds
Destroy(gameObject); // destroy gameObject that script is attached to
}
This is a valid alternate strategy which I generally prefer (letting things self-manage).
Note this answer is in JS, and the OP is using C#
Your answer
Follow this Question
Related Questions
Delete object with key within Trigger 1 Answer
How to destroy only a clone in Unity 3d? 0 Answers
Bullet shooting in the wrong angle. 0 Answers
Stuck With this codes. 1 Answer
Easy question: X axis overriding Y. Please help! :D 0 Answers