- Home /
Destroying Collected Objects / Playing Audio
Hi guys,
I've got some pickups in my game that you collect by colliding with them. They are then destroyed and a number is added to your objects counter. Here is (some of) the code I have written:
else if(hit.gameObject.tag == "Helmet1") {
audio.PlayOneShot(pickup);
Destroy(hit.gameObject);
OBJECTNUMBER += 1;
g_Helmet.animation.Play("g_Inv_HelmetAnimation2");
print("you now have" + OBJECTNUMBER);
}
}
Now. This works fine, but what happens is because the audio source is set to the object, and then the object gets destroyed, the sound doesn't play. So to combat this, I put in a yield here:
else if(hit.gameObject.tag == "Helmet1") {
audio.PlayOneShot(pickup);
yield(1); Destroy(hit.gameObject); OBJECTNUMBER += 1; g_Helmet.animation.Play("g_Inv_HelmetAnimation2"); print("you now have" + OBJECTNUMBER);
}
}
This enabled the sound to play before the object was destroyed - but - now sometimes the OBJECTNUMBER goes up by two or three, because I am still colliding with the object.
How can I write the code so that it only goes up by 1, and the pickup sound can play?
Thanks!
Answer by ThumbStorm · May 03, 2010 at 12:25 AM
You could add the sound to the camera or any game object that wouldn't be destroyed. Just add this to the top of the script:
var soundObj : GameObject;
then use soundObj.audio.PlayOneShot(pickup);
with this you can use the first script and get rid of yield.
Thanks this works, however I get a weird click sound the first time the audio plays, unless I turn play on awake on. Do you know of any reason why this would occur?
Thanks
Answer by aburningflame · Jan 25, 2014 at 09:34 PM
I dont get a click sound with Play On Awake on.
C# Solution: GameObject>Create Empty>Name it something (I named it Engine) Select the Gameobject in the Hierarchy Component>Add Component>Audio>Audio Source
Enemy.cs
private GameObject engine;
void Start () {
direction=Direction.UP;
engine=GameObject.Find ("Engine");
}
public void TakeDamage(int amt){
hp-=amt;
if(hp<=0){
engine.audio.PlayOneShot (deathSound);
Destroy(gameObject);
}
}
Your answer
Follow this Question
Related Questions
There is no 'audioSource' attached to the game object error 1 Answer
Play music troughout whole game in js 1 Answer
Audio Clip constantly play 1 Answer
Audio is repeating. 3 Answers
On Mouse Click Play Sound 1 Answer