Triggering an audio clip randomly from an array of audio clips.

Hi, I’m trying to trigger an audio clip randomly from an array of audio clips.

I’ve looked around the forums and see other people have posted this topic, but i haven’t been able to make other people’s solutions work for some reason.

Any feedback would be great.

public class RandomSound : MonoBehaviour
{

    public bool playedClip = false;
    public GameObject player;
    public GameObject Sound_Array;
    public string[] _audioNames = new string[] { "Sound1", "Sound2", "Sound3" };

    // Use this for initialization
    void Start()
    {
        GameObject Sound_Array = GameObject.Find("Sound_Array");
        Sound_Array.GetComponent<AudioClip>();
        Sound_Array.GetComponent<AudioSource>();
    }

    public void OnTriggerEnter(Collider p)
    {

        if (p.gameObject.name == "Player" && !playedClip)
        {
            Debug.Log("Player triggered");

            playedClip = true;

            Sound_Array.GetComponent<AudioSource>().PlayOneShot(_audioNames[Random.Range(0, _audioNames.Length)]);

        }
    }
}

Your code has 1 major flaw and 2 mini flaws
In Start(), do not re-declare ‘Sound_Array’.

Sound_Array = GameObject.Find  ... etc * your code *
// instead of GameObject Sound_Array ... etc

The way you wrote it, means you’ve created a local scope variable, that can only be used from that point on, in that method only. Meaning, later when you try to access it, it’s unassigned. (You could mention errors when you post code to help with this.

Second mini issues are in Start, also. Your two calls to GetComponent do absolutely nothing, because you have not assigned their results. You call methods that return references… but do not store them anywhere. This doesn’t really hurt you, because later you’re just looking up the AudioSource again, anyways. But it doesn’t hurt to know :slight_smile:

1 Like

This works for me;

    public AudioClip[] AudioClipArray;

    private AudioSource _audioSource;
    // Use this for initialization
    void Start ()
    {
        _audioSource = GetComponent<AudioSource>();
    }
   
    // Update is called once per frame
    void Update () {
        if (!_audioSource.isPlaying)
        {
            _audioSource.clip = AudioClipArray[Random.Range(0, AudioClipArray.Length)];
            _audioSource.Play();
        }
    }
1 Like

Nice. I didn’t think those strings would work for audio clips, but neglected to include a proper response to address that. :slight_smile:

People, thank you all so much for your help. It’s an absolute blast when code works.

You’re welcome :slight_smile: Glad ya got it working.