You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity协程满足条件后无法停止的问题求助

Unity协程无法停止的问题修复

问题根源

你代码里的核心问题是:就算触发了StopAllCoroutines(),之后代码还是会执行到StartCoroutine(startCounting()),相当于刚停掉协程又立刻重启了,自然停不下来。另外还有两个小问题:Update()每帧调用FindGameObjectsWithTag()太耗性能,而且用递归调用协程的方式实现循环本身就容易出问题。

修复方案

改成循环结构的协程,条件满足时直接终止,同时优化敌人数量的检测逻辑:

using System.Collections;
using UnityEngine;

public class EnemyCounter : MonoBehaviour
{
    private Coroutine _countingRoutine;
    private int _count;

    private void Start()
    {
        // 启动协程并保存引用
        _countingRoutine = StartCoroutine(StartCounting());
    }

    IEnumerator StartCounting()
    {
        while (true)
        {
            _count++;
            yield return new WaitForSeconds(1);
            Debug.Log("CURRENT COUNTER IS " + _count);

            // 直接在协程里检测敌人数量,不用每帧在Update里刷新
            GameObject[] enemies = GameObject.FindGameObjectsWithTag("enemyCollider");
            
            if (enemies.Length == 3 || enemies.Length == 6)
            {
                Debug.Log("ENEMY COUNTER HAS REACHED " + _count);
                // 直接终止协程,无需调用StopAllCoroutines
                yield break;
            }
        }
    }

    // 如果需要外部手动停止,可以加这个方法
    public void StopCounting()
    {
        if (_countingRoutine != null)
        {
            StopCoroutine(_countingRoutine);
            _countingRoutine = null;
        }
    }
}

关键改动说明

  • 用while(true)循环代替递归调用协程,逻辑更清晰,终止时直接用yield break即可,不会出现重启的问题。
  • 把敌人数量检测移到协程内部,每1秒检测一次,比Update()每帧检测节省性能。
  • 保存协程引用到_countingRoutine,如果需要外部停止(比如其他逻辑触发),可以调用StopCounting()方法精准停止,不用粗暴的StopAllCoroutines()。

内容的提问来源于stack exchange,提问作者Nicole Erasga

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 04:01:42