- Home /
Sound on collisions
Im sorry that im posting this again.. But i cant seem to find a way to get this right.'m probably missing something simple :/.. I thought I had it right with the help I got last time I posted..
As it is, I have a simple cube set up to be destroyed on Collision with a particle effect as the explosion, but I cant for the life of me get sound to play on the collision.. Thank you in advance for the help.
Here is the code Im using:
#pragma strict
var stars : ParticleEmitter;
var Sound : AudioClip;
function OnTriggerEnter (collision : Collider) {
if (collision.gameObject.name == "Player")
{
Instantiate(stars, transform.position, transform.rotation);
audio.PlayOneShot(Sound);
Destroy(gameObject);
}
}
As far as i can see, you dont actually seem to be referencing the actuall sound file you want to play.
You have Sound setup as an audio clip, but do you not need a reference to the actually file somewhere?
Answer by Berenger · Mar 19, 2012 at 03:49 PM
As a sound is an audioclip played by an audiosource, and as audiosource is a component which, like all components, only leaves as long as it's gameobject, your sound is destroyed as soon as it starts. You have two possibilities :
Create an empty game object (new GameObject(..)) add an AudioSource, give the audioclip ref and tell it to play. Use Destroy( thatNewGO, Sound.Length ) to destroy the gameobject once the sound is played. By the way, you could also do that for the initial gameobject, but I guess you have other script that you don't want anymore, renderers and stuff.
Attach the sound to the particle system's game object and make sure it plays on awake.
Your answer
Follow this Question
Related Questions
HELP!!! Sound won't play upon Collision! Script looks correct... 2 Answers
Making a sound using collisions 1 Answer
help sound on collision when key down 2 Answers
How to reproduce a sound when my character collide 1 Answer
What is the best way to script third person real-time action melee combat in C#? 0 Answers