- Home /
How do I Destroy() powerup and get sound to play?
Hello everyone. I have a powerup and I'm trying to get a sound to play when it's picked up, however if I destroy the powerup that the sound component is attached to it won't play. I then figured I could disable the renderer on the object until the sound plays, then delete the object and the sound, but this didn't work because although the object is invisible it can still be picked up multiple times before it gets destroyed.
My player collides with a crate, the powerup gets instantiated and a sound is played. After 2 seconds all three are destroyed. How can I do this?
var crateCollectionSnd:GameObject;
var minesCollected:GameObject;
function Update () {
}
function OnTriggerEnter(col:Collider){
if(col.gameObject.tag == "Player"){
GameObject.Find("PlayerPrefab").GetComponent(FireScript).Mines();
var cloneSound = Instantiate(crateCollectionSnd, transform.position, transform.rotation);
var cloneMinesCollected = Instantiate(minesCollected, transform.position, Quaternion.Euler(Vector3(0,180,0)));
renderer.enabled = false;
yield WaitForSeconds(2);
Destroy(cloneMinesCollected);
Destroy(cloneSound);
Destroy(gameObject);
}else if(col.gameObject.tag == "Bullet" || col.gameObject.tag == "EnemyBullet"){
Destroy(gameObject);
}else if(col.gameObject.tag == "Enemy"){
Destroy(gameObject);
}
}
Answer by slkjdfv · Apr 24, 2012 at 05:16 PM
Have you tried adding a boolean called canPickup? and placing it after col.gameObject.tag == "Player"? and if it's true then set it to false. It whould look like this :
var crateCollectionSnd:GameObject;
var minesCollected:GameObject; private var canPickup:boolean = true;
function Update () {
}
function OnTriggerEnter(col:Collider) { if(col.gameObject.tag == "Player" and canPickup) { canPickup = false; GameObject.Find("PlayerPrefab").GetComponent(FireScript).Mines(); var cloneSound = Instantiate( crateCollectionSnd, transform.position, transform.rotation); var cloneMinesCollected = Instantiate(minesCollected, transform.position, Quaternion.Euler(Vector3(0,180,0)));
renderer.enabled = false;
yield WaitForSeconds(2);
Destroy(cloneMinesCollected);
Destroy(cloneSound);
Destroy(gameObject);
}else if(col.gameObject.tag == "Bullet" || col.gameObject.tag == "EnemyBullet"){
Destroy(gameObject);
}else if(col.gameObject.tag == "Enemy"){
Destroy(gameObject);
}
}
Your answer
Follow this Question
Related Questions
Destroying a gameobject clone after a time 3 Answers
Destroy Clones One At A Time Javascript 0 Answers
Instantiate and Destroy an object while crossing a line with its clone also 1 Answer
Problem with timed code-execution (audioplay and object destruction) 1 Answer
using Contains(gameObject) to find and destroy a gameObject from a list 2 Answers