- Home /
"Or" operator or random
Hello. I'm trying to play a random sound from 5 or nvm how much ones, but dont mind how it should work. I've tryed to use "||", but no results:
audioSource.PlayOneShot(sound1 || sound2, 0.7F);
also, I've tryed to manipulate with Random, but didnt get my aim. Help me please.
Answer by ray2yar · Jan 26, 2019 at 07:59 PM
Here's some pseudo code for you:
Have a public array of all your sounds Select a random index Play the sound in that index
Something like this:
public AudioClip[] Sounds; //assign all your sounds here
void PlayRandom()
{
int rand = Random.Range(0,Sounds.Length);
audioSource.PlayOneShot(Sounds[rand], 0.7f);
}
Answer by xxmariofer · Jan 26, 2019 at 08:03 PM
hello, have all the audios in a list or in a array, create a random from 0 to the numberofclips and put use that cllip. example
audioSource.PlayOneShot(listOfClipds[Random.Range(0, listOfClips.Count)], 0.7f)
Answer by BastianUrbach · Jan 27, 2019 at 11:38 AM
The other answers are great but in the interest of keeping things tidy and readable, here is a neat self contained function that works with any type:
static T PickRandom<T>(params T[] options) {
return options[Random.Range(0, options.Length)];
}
You can use it like this:
audioSource.PlayOneShot(PickRandom(sound1, sound2), 0.7F);
Your answer
![](https://koobas.hobune.stream/wayback/20220612190526im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Random movement script not working C# 2 Answers