Triggering random sound on player

I’m using the following script to trigger one of a group of random sounds when I enter a trigger zone. The sounds are coming from the same game object.

I want to do something similar, but have the trigger zone trigger sounds on the Player rather than from that game object. I also want it to cycle through the different sounds rather than just playing one and stopping, with a small wait period between each sound, and for it to stop when I leave the zone.

I’ve played around with other other.gameObject.GetComponent but I don’t quite understand it. :confused:

Any help is greatly appreciated!

var isPlaying : boolean = false;
var thisSound : AudioSource;
var myClips : Object[];
var sounds: AudioClip[];
 

function OnTriggerEnter(){
    if(isPlaying == false){
        isPlaying = true;
        audio.clip = sounds[Random.Range(0,sounds.length)];
        audio.Play();
    }
}

function OnTriggerExit(){
    if(isPlaying == true){
        isPlaying = false;
    }
}

You shouldn’t need GetComponent at all, but what you do need is a Coroutine.

using UnityEngine;
using System.Collections;

[RequireComponent(typeof(AudioSource), typeof(SphereCollider))]
public class RandomSoundPlayer : MonoBehaviour
{
	public AudioClip[] clips;

	#region Unity
	void OnValidate()
	{
		collider.isTrigger = true;
	}

	void OnTriggerEnter()
	{
		if (containedColliderCount++ == 0)
			StartCoroutine(PlayRandomSound());
	}

	void OnTriggerExit()
	{
		if (--containedColliderCount == 0)
			StopPlaying();
	}
	#endregion

	#region Private
	private int containedColliderCount;
	
	private AudioClip RandomClip
	{
		get
		{
			return clips[(int)(Random.value * clips.Length)];
		}
	}

	void StopPlaying()
	{
		audio.Stop();
	}

	void PlayClip(AudioClip clip)
	{
		audio.clip = clip;
		audio.Play();
	}

	IEnumerator PlayRandomSound()
	{
		while (containedColliderCount > 0)
		{
			if (!audio.isPlaying)
				PlayClip(RandomClip);
			yield return null;
		}
		StopPlaying();
	}
	#endregion
}

What happens is that you add your clips, then start a coroutine when the first collider, and only the first collider, enters your trigger. This coroutine monitors the playing state of your audio source, and picks a new random clip to play if it isn’t playing. When the last contained collider exits your trigger, you stop playing your sound.