随机音频超过随机间隔在统一
本文关键字:随机 音频 | 更新日期: 2023-09-27 18:07:26
基本上,我正在制作一款Unity游戏。我需要一些音频剪辑随机循环在随机间隔和播放。至于现在,我已经写了一个脚本,应该这样做,但我有问题。下面是脚本:
using UnityEngine;
using System.Collections;
public class AudioController : MonoBehaviour
{
[SerializeField] private AudioClip[] clips;
private int clipIndex;
private AudioSource audio;
private bool audioPlaying = false;
void Start()
{
audio = gameObject.GetComponent<AudioSource>();
}
void Update()
{
StartCoroutine(PlaySound());
}
IEnumerator PlaySound()
{
yield return new WaitForSeconds(Random.Range(10f, 20f));
audioPlaying = false;
if (!audioPlaying)
{
clipIndex = Random.Range(0, clips.Length - 1);
audioPlaying = true;
audio.PlayOneShot(clips[clipIndex], 1f);
}
yield return new WaitForSeconds(Random.Range(10f, 20f));
}
}
基本上,在调试时,我发现audioPlaying仍然为真,并且clipIndex不断地通过索引循环。最后,所有的声音都不停地播放,发出巨大的嗡嗡声。我的问题是audioPlaying没有禁用,等待时间不一定是工作的结果。谢谢,任何帮助都会很感激!
你的工作错误调用每个Update到协程和设置为false audioplaying和播放一个新的声音。试试这个:
using UnityEngine;
using System.Collections;
public class AudioController : MonoBehaviour
{
[SerializeField] private AudioClip[] clips;
private int clipIndex;
private AudioSource audio;
private bool audioPlaying = false;
void Start()
{
audio = gameObject.GetComponent<AudioSource>();
}
void Update()
{
if (!audio.isPlaying)
{
clipIndex = Random.Range(0, clips.Length - 1);
audio.clip = clips[clipIndex];
audio.PlayDelayed(Random.Range(10f, 20f));
Debug.Log("Nothing playing, we set new audio to " + audio.clip.name);
}
}
因为每一帧你都有一些东西看起来像这样:
audioPlaying = false;
if (!audioPlaying)
{
audioPlaying = true;
}
你看到问题了吗?不妨这样写:
if (true)
{
audioPlaying = true;
}
无论如何,你可以试试:
void Start()
{
StartCoroutine(PlaySound());
}
IEnumerator PlaySound()
{
yield return new WaitForSeconds(Random.Range(10f, 20f));
clipIndex = Random.Range(0, clips.Length - 1);
audio.PlayOneShot(clips[clipIndex], 1f);
yield return new WaitForSeconds(clips[clipIndex].length);
StartCoroutine(PlaySound());
}
易于修复:
using UnityEngine;
using System.Collections;
public class AudioController : MonoBehaviour
{
public AudioClip[] clips;
private int clipIndex;
private AudioSource audio;
private bool audioPlaying = false;
void Start()
{
audio = gameObject.GetComponent<AudioSource>();
}
void Update()
{
if (!audio.isPlaying)
{
clipIndex = Random.Range(0, clips.Length - 1);
audio.clip = clips[clipIndex];
audio.PlayDelayed(Random.Range(20f, 50f));
Debug.Log("Nothing playing, we set new audio to " + audio.clip.name);
}
}
}