- Home /
Question by
XsettingsX · Oct 09, 2020 at 12:23 PM ·
programmingaudiosourcemusicaudioclips array
how to choose random music
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Music : MonoBehaviour
{
public AudioClip[] musicArray;
public AudioSource source;
int CurrentSong;
private void Awake()
{
source = GetComponent<AudioSource>();
}
void Start()
{
CurrentSong = Random.Range(0, musicArray.Length);
}
private void Update()
{
source.clip = musicArray[CurrentSong];
source.PlayOneShot(source.clip);
if (source.isPlaying == false)
{
CurrentSong += 1;
}
}
}
ok so im pretty sure that if
if (source.isPlaying == false)
{
CurrentSong += 1;
}
is my current problem, I can get a random audio to play from the array however I then want to shuffle through the array in order after it picks a random. Any clues are welcome :)
Comment
Answer by XsettingsX · Oct 09, 2020 at 12:37 PM
actually, don't worry guys, i got it working
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Music : MonoBehaviour
{
public AudioClip[] musicArray;
public AudioSource source;
int CurrentSong;
private void Awake()
{
source = GetComponent<AudioSource>();
}
void Start()
{
CurrentSong = Random.Range(0, musicArray.Length);
source.clip = musicArray[CurrentSong];
source.PlayOneShot(source.clip);
}
private void Update()
{
if (source.isPlaying == false)
{
CurrentSong += 1;
source.clip = musicArray[CurrentSong];
source.PlayOneShot(source.clip);
}
if(CurrentSong>= musicArray.Length)
{
CurrentSong = 0;
}
}
}