- Home /
Audio Script
Can someone help me out. I need a script so if someone with the tag Player steps on a box collider a audio sound plays. This would attach to the box collider. Also can you tell me how to make the audio clip a variable.
Answer by aldonaletto · Aug 29, 2011 at 04:57 PM
It's easy: declare an AudioClip variable and use PlayClipAtPoint to play the sound without needing to add a AudioSource component to the box:
var sound: AudioClip;
function OnTriggerEnter(col: Collider){ if (col.tag == "Player"){ AudioSource.PlayClipAtPoint(sound, transform.position); } } Remember to set isTrigger in the collider. If you don't want it to be a trigger, you can use OnCollisionEnter:
var sound: AudioClip;
function OnCollisionEnter(col: Collision){ if (col.gameObject.tag == "Player"){ AudioSource.PlayClipAtPoint(sound, transform.position); } } In any case, the sound will play only once when the player enters or touches the box collider, and repeat only if the player exits and enters the collider again. sound is a variable like any other, so you can modify its value by script, if you want.
Which did you use: OnTrigger or OnCollider? Place a debug instruction like print("Player entered") before if (col....) to check if the collision/trigger is working fine (they're a frequent headache cause).
Your answer
Follow this Question
Related Questions
Change Pitch on Collision 1 Answer
Sound on collision 3 Answers
Detect RaycastHit on Character Controller 2 Answers
Collision of 2 objects, which one should be is-Kinematic 1 Answer
Colliders don't work 1 Answer