Unity协程循环失效:火炬亮灭动画无限循环实现求助
火炬亮灭循环的实现方案
原代码失效大概率是Animator状态机的自动过渡或动画设置冲突导致的,下面给你几种可靠的实现方式:
方案一:用Animator参数控制(推荐)
这是最符合Unity动画工作流的方式,能避免直接调用Play带来的冲突:
- 打开你的Animator控制器,添加一个布尔类型参数,命名为
IsTorchOn - 给点亮、熄灭两个动画状态设置双向过渡:
- 从熄灭状态到点亮状态:条件设为
IsTorchOn = true,取消勾选Has Exit Time - 从点亮状态到熄灭状态:条件设为
IsTorchOn = false,同样取消Has Exit Time
- 从熄灭状态到点亮状态:条件设为
- 替换成以下代码:
Animator anim; bool torchIsOn = false; void Start() { anim = GetComponent<Animator>(); // 0秒后开始,每3秒触发一次切换 InvokeRepeating(nameof(ToggleTorch), 0f, 3f); } void ToggleTorch() { torchIsOn = !torchIsOn; anim.SetBool("IsTorchOn", torchIsOn); }
方案二:修复原协程代码
如果想保留协程的写法,先排查两个关键点:
- 确认动画名称完全匹配,包括大小写、符号(比如横杠是否正确)
- 关闭动画的Loop Time选项,避免动画自动循环覆盖代码逻辑
然后修改协程,添加停止当前动画的操作:
Animator anim; void Start() { anim = GetComponent<Animator>(); StartCoroutine(TorchCycle()); } IEnumerator TorchCycle() { while(true) { anim.Stop(); // 先停止当前动画,防止冲突 anim.Play("firetorchon-Animation"); yield return new WaitForSeconds(3); anim.Stop(); anim.Play("firetorchoff-Animation"); yield return new WaitForSeconds(3); } }
方案三:用InvokeRepeating直接切换动画
这种写法更简洁,适合简单的状态切换:
Animator anim; bool isTorchOn = false; void Start() { anim = GetComponent<Animator>(); // 先播放点亮动画,3秒后开始循环切换 anim.Play("firetorchon-Animation"); InvokeRepeating(nameof(SwitchTorchState), 3f, 3f); } void SwitchTorchState() { isTorchOn = !isTorchOn; anim.Play(isTorchOn ? "firetorchon-Animation" : "firetorchoff-Animation"); }
内容的提问来源于stack exchange,提问作者oliver oliver
相关产品推荐
相关产品推荐

