You need to enable JavaScript to run this app. Unity C# 切换移动方向时取消未完成精灵动画避免叠加
优惠活动
大模型
产品
解决方案
定价
更多

Unity C# 切换移动方向时取消未完成精灵动画避免叠加

四方向行走动画精灵叠加问题修复方案

核心问题定位

你现在的脚本有两个硬伤,直接导致了精灵叠加、切换方向不生效的问题:

  • 完全没保存协程的运行引用,只要检测到有移动输入,每帧Update都会新开一个ChangeSprite协程。多个协程并行运行时会交替修改sprite的显示值,视觉上就会出现不同方向的精灵闪烁、甚至叠加。
  • 你写的StopCoroutine(ChangeSprite())根本停不掉正在运行的协程:Unity的StopCoroutine必须传入之前启动时缓存下来的协程实例,或者启动时用的字符串方法名,直接传IEnumerator方法的引用是匹配不到正在运行的协程的,这也是为什么停下角色的时候动画不会立刻终止。

具体修改步骤

1. 新增协程缓存变量

在类的字段区域加一个变量,专门存当前正在运行的行走动画协程:

// 缓存当前运行的行走动画协程,方便后续停止
private Coroutine _currentWalkAnim;

2. 重构Update里的协程启停逻辑

把原来无脑启动协程的逻辑换成「先停旧协程,再开新协程」的流程,从根源上避免多个协程并行:

void Update()
{
    bool isMoving = playerController.vertical != 0f || playerController.horizontal != 0f;
    // 处于移动状态时
    if (isMoving)
    {
        // 先停掉上一次启动的动画
        if (_currentWalkAnim != null)
        {
            StopCoroutine(_currentWalkAnim);
        }
        // 启动新方向的动画,把协程实例缓存起来
        _currentWalkAnim = StartCoroutine(ChangeSprite());
    }
    // 角色停下时
    else
    {
        if (_currentWalkAnim != null)
        {
            StopCoroutine(_currentWalkAnim);
            _currentWalkAnim = null;
            // 这里可以设置角色站立时的静态精灵,避免停在走路帧上
            // spriteRenderer.sprite = moveArray[对应站立帧的索引];
        }
    }
}

3. 优化协程内部的判断逻辑

你原来的协程是单次跑完4帧就退出,所以才需要每帧Update反复触发,其实完全可以在协程内部循环播放对应方向的帧序列,减少冗余代码:

优化后的ChangeSprite参考写法,同时修正了你原来的方向判断bug(原来的判断直接带符号比较值,斜向输入时会触发多个if块):

IEnumerator ChangeSprite()
{
    int frameStartIndex;
    // 右方向
    if (playerController.horizontal >= .1f && Mathf.Abs(playerController.horizontal) > Mathf.Abs(playerController.vertical))
    {
        frameStartIndex = 6;
    }
    // 左方向
    else if (playerController.horizontal <= -.1f && Mathf.Abs(playerController.horizontal) > Mathf.Abs(playerController.vertical))
    {
        frameStartIndex = 3;
    }
    // 下方向
    else if (playerController.vertical <= -.1f && Mathf.Abs(playerController.vertical) > Mathf.Abs(playerController.horizontal))
    {
        frameStartIndex = 0;
    }
    // 上方向
    else
    {
        frameStartIndex = 9;
    }
    // 循环播放该方向的行走帧序列:起始帧 → 中间帧 → 抬起帧 → 中间帧
    while (true)
    {
        spriteRenderer.sprite = moveArray[frameStartIndex];
        yield return new WaitForSeconds(0.3f);
        spriteRenderer.sprite = moveArray[frameStartIndex + 1];
        yield return new WaitForSeconds(0.3f);
        spriteRenderer.sprite = moveArray[frameStartIndex + 2];
        yield return new WaitForSeconds(0.3f);
        spriteRenderer.sprite = moveArray[frameStartIndex + 1];
        yield return new WaitForSeconds(0.3f);
    }
}

注意事项

  • 如果暂时不想重构协程结构,最少也要加上协程缓存、切换方向先停旧协程的逻辑,否则就算解决了精灵叠加的问题,也会因为每帧攒新协程导致动画播放速度越来越快。
  • 比较两个输入轴的强度时,一定要用Mathf.Abs()取绝对值,否则负数值会让判断逻辑完全错乱,比如水平输入-1、垂直输入0的时候,因为-1 < 0,根本进不了左方向的判断分支。

内容的提问来源于stack exchange,提问作者Donald Puggini

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.22 20:57:02