- Home /
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
}
Answer by aldonaletto · Nov 20, 2011 at 03:57 PM
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.
Answer by henry96 · Nov 20, 2011 at 03:46 PM
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.
Answer by himanshu619 · Dec 07, 2012 at 04:21 PM
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.
Hey it doesnt work... i added the script to the object to collect and i collected it and no audio sounded... Y
This is because you haven't added any sound in your script (under inspector window). Add any sound in the script (from inspector window). $$anonymous$$ark this answer as right and do get back to me if it still not work for you.