基本上,我正在制作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没有被禁用,等待时间不一定会因此而起作用。谢谢,任何帮助将不胜感激!
答案 0 :(得分:2)
你的工作错误调用协程的每个更新并设置为错误的音频播放和播放新声音。 试试这个:
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);
}
}
答案 1 :(得分:1)
因为每一帧你都有这样的东西:
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());
}
答案 2 :(得分:0)
易于修复:
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);
}
}
}