Unity中IEnumerator协程WaitForSeconds失效问题求助
问题分析
你的代码里协程只执行单次动画切换流程,跑完一轮就终止了;后续的动画频繁跳转不是协程触发的,大概率是Animator状态机存在无条件自动过渡(比如开启了Has Exit Time但没加过渡条件),或者触发器信号没被正确消耗导致重复触发。另外代码里先启动协程再获取Animator组件,存在潜在空引用风险。
解决方案
1. 给协程加循环逻辑
让协程持续重复等待-动画切换的流程,确保动画能周期性触发。
2. 调整组件初始化顺序
先获取Animator组件再启动协程,避免空引用异常。
3. 修正Animator状态机配置
打开Animator面板检查:
- 两个动画状态的过渡仅通过对应Trigger触发,关闭不必要的
Has Exit Time,避免动画播放完自动跳转。 - 若Trigger仍有异常,可改用Bool参数控制状态,逻辑更稳定。
修改后的代码
using System.Collections; using UnityEngine; public class AnimateEveryNTime : MonoBehaviour { private Animator animator; private void Start() { // 先获取组件再启动协程 animator = GetComponent<Animator>(); StartCoroutine(PlayAnimationLoop()); } private IEnumerator PlayAnimationLoop() { // 无限循环执行动画切换逻辑 while (true) { yield return new WaitForSeconds(10f); animator.SetTrigger("trapActivate"); yield return new WaitForSeconds(10f); animator.SetTrigger("trapInactive"); // 可选:若触发器残留触发,可手动重置 // animator.ResetTrigger("trapActivate"); // animator.ResetTrigger("trapInactive"); } } }
替代方案(用Bool参数更稳定)
如果Trigger仍出现异常跳转,推荐用Bool参数控制状态:
private IEnumerator PlayAnimationLoop() { while (true) { yield return new WaitForSeconds(10f); animator.SetBool("IsTrapActive", true); yield return new WaitForSeconds(10f); animator.SetBool("IsTrapActive", false); } }
同时在Animator状态机中,将过渡条件设置为IsTrapActive的true/false值,取消Trigger的使用。
内容的提问来源于stack exchange,提问作者Mad
相关产品推荐
相关产品推荐

