basicly i have some mp3 files in the assets folder and i want to make a c# script that reproduce one of those tracks ramdomly selected and when it finish it repeats the script so it constantly reproduces ramdom music, and i want that if you press a button it will change to another ramdom song like in sanicball wich was make on unity, so, i literaly downloaded unity a few days ago and open it today
-C#:
using UnityEngine;
public class RandomAudioClipPlayer : MonoBehaviour
{
public AudioSource source = null;
public bool skip = false;
public bool preventRepeating = true;
public AudioClip[] audioClips = null;
private int randomizeIndex = 0;
private int _preventRepeating = -1;
public void Update ()
{
if(source && audioClips != null)
{
if(!source.isPlaying || skip)
{
skip = false;
source.Stop();
randomizeIndex = Random.Range(0,audioClips.Length);
if(randomizeIndex != _preventRepeating || !preventRepeating)if(audioClips[randomizeIndex])
{
source.clip = audioClips[randomizeIndex];
source.Play();
}
if(preventRepeating)_preventRepeating = randomizeIndex;
}
}
if(!source && GetComponent<AudioSource>())source = GetComponent<AudioSource>();
}
public void Source (AudioSource m_value) {if(source != m_value)source = m_value;}
public void Skip (bool m_value) {if(skip != m_value)skip = m_value;}
public void PreventRepeating (bool m_value) {if(preventRepeating != m_value)preventRepeating = m_value;}
public void AudioClips (AudioClip[] m_value) {if(audioClips != m_value)audioClips = m_value;}
}
-JavaScript:
public var source : AudioSource = null;
public var skip : boolean = false;
public var preventRepeating : boolean = true;
public var audioClips : AudioClip[] = null;
private var randomizeIndex : int = 0;
private var _preventRepeating : int = -1;
public function Update ()
{
if(source && audioClips)
{
if(!source.isPlaying || skip)
{
skip = false;
source.Stop();
randomizeIndex = Random.Range(0,audioClips.Length);
if(randomizeIndex != _preventRepeating || !preventRepeating)if(audioClips[randomizeIndex])
{
source.clip = audioClips[randomizeIndex];
source.Play();
}
if(preventRepeating)_preventRepeating = randomizeIndex;
}
}
if(!source && GetComponent.<AudioSource>())source = GetComponent.<AudioSource>();
}
public function Source (m_value : AudioSource) {if(source != m_value)source = m_value;}
public function Skip (m_value : boolean) {if(skip != m_value)skip = m_value;}
public function PreventRepeating (m_value : boolean) {if(preventRepeating != m_value)preventRepeating = m_value;}
public function AudioClips (m_value : AudioClip[]) {if(audioClips != m_value)audioClips = m_value;}
Thank Me Later
[EDIT] The Script Is Edited And Fixed Some Bugs.