我正在用迷宫制作游戏,并带有声音提示如何走。我在协程上播放声音,并且只能启动一次。但是,我需要做的是能够在打开触发器的情况下从另一个脚本中停止它,以便当播放器经过某个点时音频不会继续播放。到目前为止,这是我的代码。
public AudioSource direction;
private bool running = false;
IEnumerator AudioPlay()
{
while (true)
{
direction.Play();
yield return new WaitForSeconds(2);
}
}
void OnTriggerEnter(Collider col)
{
if (col.gameObject.CompareTag("Player"))
{
if (running == false)
{
StartCoroutine(AudioPlay());
Debug.Log("Started");
running = true;
}
else if (running == true)
{
Debug.Log("Void");
}
}
}
答案 0 :(得分:1)
StopCoroutine(previouslyRunCoroutine)
如果您使用IEnumerator
表单(StartCoroutine(AudioPlay());
)启动协程,则Unity文档recommends将保存对IEnumerator
的引用并在以后使用致电StopCoroutine
:
public AudioSource direction;
private bool running = false;
public IEnumerator audioPlayCoroutine;
IEnumerator AudioPlay()
{
while (true)
{
direction.Play();
yield return new WaitForSeconds(2);
}
}
void OnTriggerEnter(Collider col)
{
if (col.gameObject.CompareTag("Player"))
{
if (running == false)
{
audioPlayCoroutine = AudioPlay();
StartCoroutine(audioPlayCoroutine);
Debug.Log("Started");
running = true;
}
else if (running == true)
{
Debug.Log("Void");
}
}
}
然后,在其他脚本中,您可以使用StopCoroutine
:
OtherScript.StopCoroutine(OtherScript.audioPlayCoroutine);
如果要使用诸如StartCoroutine("AudioPlay");
之类的方法名形式,则文档建议使用方法名形式来停止它:
OtherScript.StopCoroutine("AudioPlay");