当玩家点击触发器时,我需要停止在另一个脚本中运行的协程。触发器起作用,但是协程不会停止。
以下是运行协程的脚本:
public AudioSource direction;
public IEnumerator audioPlayCoroutine;
public 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)
{
audioPlayCoroutine = AudioPlay();
StartCoroutine(audioPlayCoroutine);
Debug.Log("Started");
running = true;
}
else if (running == true)
{
Debug.Log("Void");
}
}
}
这是停止协程运行的脚本。
public GameObject lastTrigger;
void OnTriggerEnter(Collider col)
{
if (col.gameObject.CompareTag("Player"))
{
Debug.Log("Triggered");
if (lastTrigger.GetComponent<MazeAudioLoop>().running == true)
{
lastTrigger.GetComponent<MazeAudioLoop>().running = false;
Debug.Log("Running: false");
StopCoroutine(lastTrigger.GetComponent<MazeAudioLoop>().audioPlayCoroutine);
}
}
}
显示触发的调试,但是协程不会停止。
答案 0 :(得分:1)
您需要在运行协程的组件上调用StopCoroutine。
StopCoroutine(lastTrigger.GetComponent<MazeAudioLoop>().audioPlayCoroutine);
这意味着当前组件即将停止不持有的协程。
相反,您可以创建一个简单的方法来停止协程:
MazeAudioLoop mal = lastTrigger.GetComponent<MazeAudioLoop>();
if (mal.running == true)
{
mal.running = false
mal.StopAudio();
// or this => mal.StopCoroutine(mal.audioPlayCoroutine);
}
和MazeAudioLoop.cs具有:
public void StopAudio()
{
if(audioPlayCoroutine == null) { return; }
StopCoroutine(audioPlayCoroutine);
audioPlayCoroutine = null;
}