- Home /
Destorying prefab and instanstiating again?
Hi. I have a light as a prefab which is being shot. I added a script to the prefab which just updates its position to make it move. In another script attached to my weapon I have code to actually instantiate the prefab and destroy it.
//What happens when bumper is pressed
if (isSelectedSpell && SixenseInput.Controllers[1].GetButtonDown (SixenseButtons.BUMPER) && triggerIsPressed == false && freeToShoot) {
ShootLight();
}
}
//Handles shooting the light
private void ShootLight(){
if(wandLightProjectilePrefab != null){
wandLightProjectilePrefab = Instantiate(wandLightProjectilePrefab.gameObject, transform.position, transform.parent.transform.rotation) as GameObject;
StartCoroutine(ShootCooldown(5));
Destroy(wandLightProjectilePrefab, 5);
}
}
IEnumerator ShootCooldown(float cooldown){
freeToShoot = false;
yield return new WaitForSeconds(cooldown);
freeToShoot = true;
}
So basically I want the light to shoot, 5 second cool down is triggered, the object will move for 5 seconds and stick to the first surface it touches, and destroy after 5 seconds. I then want to be able to shoot again, however this part isn't working. It just doesn't make another and I'm not sure how best to solve this. Thanks for any help
Try this:
private void ShootLight()
{
if(wandLightProjectilePrefab != null)
{
wandLightProjectilePrefab = Instantiate(wandLightProjectilePrefab.gameObject, transform.position, transform.parent.transform.rotation) as GameObject;
freeToShoot = false;
Invoke("ShootCooldown", 5f); // Starts the ShootCooldown in 5 seconds.
}
}
private void ShootCooldown()
{
freeToShoot = true;
Destroy(wandLightProjectilePrefab); // Destroy the projectile prefab immediately as 5 seconds have passed.
}
@trololo I want to be ABLE to shoot after a 5 second cool down. That all works fine. The object destroys after 5 seconds, but I don't know how to make it so it can be re instantiated after its destroyed
As a side note - I suggest to not instantiate/destroy each shoot. Just instantiate projectile, after 5 seconds deactivate it (GameObject.SetActive) and on next shoot set its position/rotation and activate again.
You need to keep a separate reference to the instantiated object. Then your reference to the prefab does not get *null*ified when you destroy the instance and you can make another copy of it.