- Home /
Destroying a instantiated prefab?
know there's many questions like this one here already, iv'e tried most of them and they doesn't seem to work.*
So, what I'm trying to do (as the title says) is to destroy a instantiated prefab to prevent lag. This is my current code, which doesn't work :
using UnityEngine;
using System.Collections;
public class Shooting : MonoBehaviour
{
public Rigidbody projectile;
public float speed = 20;
public float destroyTime = 3.0f;
// Update is called once per frame
void Update()
{
if (Input.GetButtonDown("Fire1"))
{
//Shooting sounds should be played inside here.
Rigidbody instantiatedProjectile = Instantiate(projectile, transform.position, transform.rotation) as Rigidbody;
instantiatedProjectile.velocity = transform.TransformDirection(new Vector3(0, 0, speed));
Destroy(instantiatedProjectile.gameObject, destroyTime);
}
}
}
as for the sound, make sure theres an AudioSource component on this object, then make a new AudioClip in your code public AudioClip soundEffect; then (BEFORE you destroy the game object) AudioSource.PlayClipAtPoint(soundEffect, transform.position);
That code is working fine for me nobx. can you say more how it's not working? are there any errors, or is there no instantiation in the hierarchy? Put a debug.log in the input condition also, to make sure your GetButtonDown() is being called
Haven't tested it but my guess is that it is because destroy timer cannot continue countdown in Input.GetButtonDown. Change it to Input.GetButton and hold the button for given time.
destroy time is a passed parameter handled behind the scenes; shouldn't need to manage its countdown here.
Answer by ShroomWasTaken · Jul 26, 2015 at 05:50 PM
Code started working the next day somehow....
Answer by Moaid_T4 · Jul 26, 2015 at 01:45 PM
having all the code in the same script will cause problems what you can do is make another script called destroyafter and attach it to the prefab of the projectile the script would look something like this using UnityEngine; using System.Collections;
public class DestroyAfter : MonoBehaviour {
public float LifeTime=50;
void Update()
{
Destroy(gameObject,LifeTime);
}
}