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.

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.