我正在 Unity 中开发一款游戏。
我有一个声音列表。
当玩家与物体碰撞时,我想播放声音数组中的第一个声音。第二次玩家与同一个物体碰撞时,我想播放第二个声音,依此类推。
当它到达数组的末尾时,它会再次遍历列表。
所以我尝试为此创建一个循环,并在 onTrigger2d
中调用该函数。在播放器类中。
但是,它总是在每次碰撞时播放列表中的第一个声音。
这是代码:
public class PlayNotes : MonoBehaviour
{
public AudioSource adSource;
public AudioClip[] adClips;
public void PlayNote()
{
//--1.Loop through each audio clip--
for ( int i = 0; i < adClips.Length; i++)
{
//--2.Assign current audio clip to audiosource--
adSource.clip = adClips[i];
//--3.play audio--
adSource.Play();
}
}
}
答案 0 :(得分:1)
目前您正在同时启动所有声音!请记住,您的整个循环是一次性执行的。实际上,我宁愿只播放数组中的最后一个声音。
一般来说,我宁愿在您的用例中使用 AudioSource.PlayOneShot
以便不中断当前播放的声音但允许多个并发声音。例如。让声音完成混响等播放,而下一次打击已经触发下一个声音,因此它们融合在一起。如果您使用 AudioSource.Play
,它将停止播放当前剪辑而只播放新剪辑。
然后简单地为当前播放的剪辑索引添加一个计数器,例如像这样的环绕
public class PlayNotes : MonoBehaviour
{
public AudioSource adSource;
public AudioClip[] adClips;
// Index of the currently played sound
private int index;
public void PlayNote()
{
// Play current sound
// I would rather use PlayOneShot in order to allow multiple concurrent sounds
adSource.PlayOneShot(adClips[index]);
// Increase the index, wrap around if reached end of array
index = (index + 1) % adClips.Length;
}
}