我有一个播放列表,可以对歌曲进行混洗,但我想按顺序播放或混洗。如有任何帮助,我们将不胜感激:)
公开课音乐: MonoBehaviour {
public AudioClip[] clips;
private AudioSource audiosource;
void Start()
{
audiosource = FindObjectOfType<AudioSource>();
audiosource.loop = false;
}
void Update()
{
if(!audiosource.isPlaying)
{
audiosource.clip = GetRandomClip();
audiosource.Play();
}
}
private AudioClip GetRandomClip()
{
return clips[Random.Range(0, clips.Length)];
}
private void Awake()
{
DontDestroyOnLoad(transform.gameObject);
}}
发布于 2017-11-29 02:52:24
我不明白你的问题,不是就这么简单吗?
public class Music : MonoBehaviour
{
public AudioClip[] clips;
private AudioSource audiosource;
public bool randomPlay = false;
private int currentClipIndex = 0;
void Start()
{
audiosource = FindObjectOfType<AudioSource>();
audiosource.loop = false;
}
void Update()
{
if(!audiosource.isPlaying)
{
AudioClip nextClip;
if (randomPlay)
{
nextClip = GetRandomClip();
}
else
{
nextClip = GetNextClip();
}
currentClipIndex = clips.IndexOf(nextClip);
audiosource.clip = nextClip;
audiosource.Play();
}
}
private AudioClip GetRandomClip()
{
return clips[Random.Range(0, clips.Length)];
}
private AudioClip GetNextClip()
{
return clips[(currentClipIndex + 1) % clips.Length)];
}
private void Awake()
{
DontDestroyOnLoad(transform.gameObject);
}
}发布于 2018-12-09 00:08:50
之前的答案不起作用。它返回了几个错误。我已经修改了您的脚本,并使用Unity 2018.2.12f1进行了测试。
这应该添加到一个带有音频源组件的空游戏对象中。将音频剪辑拖放到剪辑字段以创建列表。
public bool randomPlay = false; // checkbox for random play
public AudioClip[] clips;
private AudioSource audioSource;
int clipOrder = 0; // for ordered playlist
void Start () {
audioSource = GetComponent<AudioSource> ();
audioSource.loop = false;
}
void Update () {
if (!audioSource.isPlaying) {
// if random play is selected
if (randomPlay == true) {
audioSource.clip = GetRandomClip ();
audioSource.Play ();
// if random play is not selected
} else {
audioSource.clip = GetNextClip ();
audioSource.Play ();
}
}
}
// function to get a random clip
private AudioClip GetRandomClip () {
return clips[Random.Range (0, clips.Length)];
}
// function to get the next clip in order, then repeat from the beginning of the list.
private AudioClip GetNextClip () {
if (clipOrder >= clips.Length - 1) {
clipOrder = 0;
} else {
clipOrder += 1;
}
return clips[clipOrder];
}
void Awake () {
DontDestroyOnLoad (transform.gameObject);
}https://stackoverflow.com/questions/47494447
复制相似问题