x


Sound stops when object is destroyed

Hi there,

I'm currently trying to build a game that requires the character to pick up some items and I want a sound to play when an item is picked up.

below is the code that I have so far

var sound:AudioSource
var CollectSound:AudioClip

function Start(){
    sound = GetComponent(AudioSource);
}

function OnTriggerEnter(theOther:Collider) {

     if(theOther.gameObject.name == "MainChar") {

       audio.PlayOneShot(CollectSound);
       yield new WaitForSeconds(1);
       Destroy(gameObject);

   }
}

@script RequireComponent(AudioSource)

now the problem that I am facing is that the sound just stops because the item is destroy and I don't really want to yield it for a second.

Is there any way that I can attach the sound to an empty gameobject and make that play instead when my character collides with the item ? or is there any way else to code this ?

more ▼

asked May 22 '10 at 12:07 PM

Fariz gravatar image

Fariz
36 4 4 5

(comments are locked)
10|3000 characters needed characters left

2 answers: sort voted first

This sounds like an ideal situation to use AudioSource.PlayClipAtPoint.

This function does exactly what you want automatically - it creates a new audio source at the position specified, and cleans up the audio source afterwards, making it a "fire and forget" style function.

To use it in your script, you'd change the code to something like this:

var collectSound : AudioClip

function OnTriggerEnter(theOther : Collider) {

     if(theOther.gameObject.name == "MainChar") {

       AudioSource.PlayClipAtPoint(collectSound, transform.position);
       Destroy(gameObject);

   }
}
more ▼

answered May 22 '10 at 12:15 PM

duck gravatar image

duck ♦♦
41k 92 148 415

thank you so much !! thats definitely what I was looking for

May 22 '10 at 12:24 PM Fariz
(comments are locked)
10|3000 characters needed characters left

I am having the same issue, but my problem is the camera is far from the player and I tweak my AudioSource ramp for each sounds. But with this, I have no choice to use the default setting..

more ▼

answered Apr 05 '12 at 10:55 PM

daivuk gravatar image

daivuk
85 1 2 3

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x1027
x764
x524
x142

asked: May 22 '10 at 12:07 PM

Seen: 2927 times

Last Updated: Apr 05 '12 at 10:55 PM