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.
Answer by Monkiman300 · Aug 08, 2016 at 12:54 PM
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 ();
}
}
Thanks! This helped me make a simple music randomizer.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class $$anonymous$$usicRandomizer : $$anonymous$$onoBehaviour
{
public AudioClip[] audioClips;
public AudioSource audioSource;
public AudioListener audioListener;
// Start is called before the first frame update
void Start()
{
audioListener = GetComponent<AudioListener>();
audioSource = gameObject.GetComponent<AudioSource>();
}
// Update is called once per frame
void Update()
{
if (!audioSource.isPlaying)
{
PlayRandom();
}
}
void PlayRandom()
{
audioSource.clip = audioClips[Random.Range(0, audioClips.Length)];
audioSource.Play();
}
}
Answer by Fredex8 · Mar 28, 2016 at 10:26 AM
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.
Answer by Miryum · Aug 22, 2021 at 11:36 AM
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
It should be Random.Range(0, sound.Length), because the second parameter is exclusive.
Your answer
Follow this Question
Related Questions
Soundarray for player is not working properly 1 Answer
Simple question on how to use multiple FMOD sounds on one object. 0 Answers
Audio Source does not contain definition for any of the Play functions... 2 Answers
How to play a random audio clip from an array in C#? 1 Answer
C# FFT and IFFT with Array Input 1 Answer