This is what i’ve learned from this page, it is in c# btw :
using UnityEngine;
using System.Collections;
public class RandomAudio : MonoBehaviour
{
public AudioClip[] soundtrack;
// Use this for initialization
void Start ()
{
if (!audio.playOnAwake)
{
audio.clip = soundtrack[Random.Range(0, soundtrack.Length)];
audio.Play();
}
}
// Update is called once per frame
void Update ()
{
if (!audio.isPlaying)
{
audio.clip = soundtrack[Random.Range(0, soundtrack.Length)];
audio.Play();
}
}
}
it is very simple yet it works it loops between the different numbers i have just tried it out and it works fine!
use if you like
here’s my version in C# - I did this so I could invoke it to play in a google cardboard vr application upon looking at (clicking ) a GameObject. Hope this helps someone.
public class MusicPlaylist : MonoBehaviour
{
//the gameObject that will play the music
public AudioSource myMusic;
public bool isOn = false;
//allow other scripts to call functions from SoundManager
public static MusicPlaylist instance = null;
//or however long your playlist is
public AudioClip[] songList = new AudioClip[3];
public int randomIndex = 0;
void Awake()
{
//check if there is already an instance of SoundManager
if (instance == null)
instance = this;
else if (instance != this)
Destroy(gameObject);
//so music continues between levels if desired
DontDestroyOnLoad(gameObject);
}
//play a single audio clip / audio effect
public void playSingle(AudioClip clip)
{
myMusic.clip = clip;
myMusic.Play();
}
//play a random selection from a playlist
public void playRandomSong()
{
randomIndex = Random.Range(0, songList.Length);
myMusic.clip = songList[randomIndex];
myMusic.Play();
Invoke("playRandomSong", myMusic.clip.length);
}
public void turnOnOff()
{
if (isOn)
{
myMusic.Stop();
isOn = false;
}
else
{
playRandomSong();
isOn = true;
}
}
}
Hi Guys, here’s an updated version of the script for this thread :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RandomAudioPlaylistLoop : MonoBehaviour
{
public AudioClip soundtrack;
// Use this for initialization
void Start()
{
if (!GetComponent<AudioSource>().playOnAwake)
{
GetComponent<AudioSource>().clip = soundtrack[Random.Range(0, soundtrack.Length)];
GetComponent<AudioSource>().Play();
}
}
// Update is called once per frame
void Update()
{
if (!GetComponent<AudioSource>().isPlaying)
{
GetComponent<AudioSource>().clip = soundtrack[Random.Range(0, soundtrack.Length)];
GetComponent<AudioSource>().Play();
}
}