- Home /
Randomly choosing sounds ?
Hi,
i have a weather system in my game and currently only one sound for the thunderstorm.
But i wan't to change this to 3 sounds and those are randomly chosen so it's not like this :
1 -->2 ---> 3 and go back to 1 and start over it's more like this :
1-->3-->1-->2 and so on
So how do i do this ?
Any suggestions ?
Answer by whydoidoit · Jul 13, 2012 at 08:55 PM
Put you audio clips in an array and then use Random.Range(0, clipArray.Length) to select an index - then play that one.
About the array how would i define an audioclip array because everytime i try to do that it gives me errors.
never$$anonymous$$d i searched google and i found it apperantly i was correct at the beginning ;D
Answer by Chimera3D · Jul 13, 2012 at 09:07 PM
Well first of all if you have only one sound you can't generate two other different sounds. If you do have three sounds then you can create an array and choose randomly which sound you want. To do this simply use Random.Range. You can say.
var sounds : AudioClip[];
var tomeBetweenThunderBolts : float;
private var timer : float;
function Update (){
var randomSound = Random.Range(1, 3);
timer += (Time.deltaTime);
if (timer >= timeBetweenThunderBolts){
gameObject.GetComponent(audioSource).clip = sounds[randomSound];
audio.Play;
timer = 0;
}
}
I didn't test it so if there's a bug let me know and I'll fix it. What you are going to do is you are going to put all of your sounds in the sounds array, then you have to set the timeBetweenThunderBolts (I couldn't think of another variable name) then you're done!
i get an error with using parts of your script : Type 'UnityEngine.AudioClip' does not support slicing.
Sorry, did something wrong no errors now, but i'm no going for a good night time sleep so i will try in the morning !
I forgot to make the sounds variable an array, sorry about that. I updated the script.
yes i now i changed it after is searched google, i'm now going to implement this
It works now ! , thanks everyone fdor the help!
oops wrong edit box this should be a comment
Your answer
Follow this Question
Related Questions
Randomized weather, little stuck 1 Answer
random prefab instantiation 2 Answers
Simple array an spawning question 6 Answers
Make an object move towards random spot on another objects edge? 1 Answer
Puzzle + Grid Instantiate - Random 2 Answers