play sound on collecting pickUp Item

Hi i want to play sound effect when coin collecting(pickup item) in my game , i use this code :

 var collectSound:AudioClip;

 function OnTriggerEnter (other:Collider) {

  if(other.gameObject.tag=="Player"){
     audio.PlayOneShot(collectSound);
     Destroy(this.gameObject.collider);
     Destroy(this.gameObject);
   }

but this part not working :

audio.PlayOneShot(collectSound);

can any one help me ?
thanks

}

You’re destroying the object before the sound finished playing. You could use PlayClipAtPoint:

function OnTriggerEnter (other:Collider) {
  if(other.gameObject.tag=="Player"){
     AudioSource.PlayClipAtPoint(collectSound, transform.position);
     Destroy(gameObject); // this destroys the collider as well
  }
}

PlayClipAtPoint creates a new temporary AudioSource instance at the point informed, which will be destroyed when the sound finishes.

I think that line of code, which you have trouble with, reqiure audio source. So simply select the object, which the sound will play from, then go to component → audio → audio source. Hope this helps.

Full working Code:

@script RequireComponent(AudioSource)

public var clip : AudioClip;

function OnTriggerEnter(hit : Collider){        
        audio.PlayClipAtPoint(clip, Vector3 (5, 1, 2)); 
        Destroy(gameObject);    
}

Now place this javascript on to the gameobject (i.e.coin) and audio source, After it in inspector window under the above script select the audio clip.