How to play a random audio clip from an array in C#?

Hello!

So I’ve made an audio array like this:

public AudioClip shoot;

And placed two audio clips inside of it. Now my question is; how do I play a random audio clip from that array? All the methods I’ve seen online used obsolete code.

USING: Unity 5.3.5f1

My code works the same, but runs a random clip every 10 seconds. I figured this may be useful to someone at some point.

using UnityEngine;
using System.Collections;

public class RandomSoundsScript : MonoBehaviour {

	public AudioSource randomSound;

	public AudioClip[] audioSources;

	// Use this for initialization
	void Start () {

		CallAudio ();
	}


	void CallAudio()
	{
		Invoke ("RandomSoundness", 10);
	}

	void RandomSoundness()
	{
		randomSound.clip = audioSources[Random.Range(0, audioSources.Length)];
		randomSound.Play ();
		CallAudio ();
	}
}

As an example, this will choose a random clip from the array and play it when you press space.

private AudioSource audioSource;
public AudioClip[] shoot;
private AudioClip shootClip;

void Start()
{
    audioSource = gameObject.GetComponent<AudioSource>();
}

void Update()
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        int index = Random.Range(0, shoot.Length);
        shootClip = shoot[index];

        audioSource.clip = shootClip;
        audioSource.Play();
    }
}

Random.Range is how you can get a random entry from any kind of array and of any length.

public AudioClip sound;
AudioSource audioSource;

     private void Start() {
        audioSource = this.GetComponent<AudioSource>();
    }

    public void PlaySound()
    {
        int rand = Random.Range(0, sound.Length);
        audioSource.clip = sound[rand];
        audioSource.Play();
    }

and call PlaySound() with GetComponent().PlaySound() from anywhere