How can I change an Audio Source’s Audio Clip via scripting? I have a single audio source and want to cycle it’s audio clip without disabling it and enabling another source. I have an array setup but the manual indicates that you can only reference its default audio clip.
I don’t know what you mean by that.
It seems that the command AudioClip; only references the default audio clip (on the inspector panel, under audio sorce, Audio Clip). I want to assign different clips to an array of variables and cycle them through the Audio Source. What I want to get at the end is an audio sorce that cycles through 12 audio clips via scripting.
Here is what I am having problems with, the assigned thingy for the track[#] =
)The numbers after AudioClip are to indicate different audioclips)
track[0] = AudioClip1;
track[0] = AudioClip2;
track[0] = AudioClip3;
track[0] = AudioClip4;
You say you want to use an array, but your code doesn’t reflect that. What you want is something like:
audio.clip = tracks[trackNumber];
Mirage - AudioSource only holds a single AudioClip, but Jessy linked you to a perfect example of switching it at runtime.
I’m not sure what you’re doing there with your array (I’m assuming assigning them all to element 0 is a typo) although if you’re specifying the audio clips via the inspector you can actually use an array and do it more neatly, ie :
var myAudioClip: AudioClip[];
I threw together a very quick script just to test that the logic worked and ended up with this :
var myAudioClip: AudioClip[];
private var currentClip : int = 0;
function Start () {
LoopClips();
}
function LoopClips() {
while (true) {
audio.clip = myAudioClip[currentClip];
audio.Play();
yield WaitForSeconds (audio.clip.length);
currentClip++;
if (currentClip >= myAudioClip.length)
currentClip = 0;
}
}
It uses a coroutine to play the first element of your array, wait till it’s done, play the second element and so on, until the end where it will loop.
Hope that’s helpful!
Thanks Scyle, thats exactialy what I was trying to do. The element 0 was a typo, Copy-paste error . Thanks for your help.
Hello Scyle! I am trying to create an array of sounds that will play the one after the other, everytime I am using the same UI button in Unity. Can you help? Thanks in advance! Your script above helped me a lot but I still haven’t find a solution.