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

Unity角色移动时Shift键切换音效异常问题及修复咨询

问题与解决

我需要实现按下左Shift键(对应Input.GetButton("Walk"))时实时切换为行走音效,松开时切回奔跑音效,但出现以下异常:

  • 按住W键开始移动的同时按下左Shift键,音效不切换;
  • 按住W键+左Shift键开始移动后松开左Shift键,音效也不切换。

将判断条件Input.GetButton("Walk")改为hAxis != 0、!Input.GetButton("Walk")改为vAxis != 0后,功能恢复正常。

相关代码如下:

void Move() 
{
    moveVec = new Vector3(hAxis, 0, vAxis).normalized;

    // Camera
    moveVec = cameraTransform.TransformDirection(moveVec); 

    moveVec *= moveSpeed;
    moveVec.y = 0;

    if (isSide && moveVec == sideVec)
    {
        moveVec = Vector3.zero;
    }
    
    // move
    transform.position += moveVec * moveSpeed * (wDown ? 0.3f : 1f) * Time.deltaTime;

    // animation
    anim.SetBool("isRun", moveVec != Vector3.zero);
    anim.SetBool("isWalk", wDown);

    // sound
    if (moveVec != Vector3.zero) 
    {
        if (Input.GetButton("Walk") && !isRunningSound)
        {
            Debug.Log("walk");
            CancelInvoke(currentSound);
            currentSound = "WalkSound";
            InvokeRepeating(currentSound, 0f, 0.7f);
            isRunningSound = true;               
        } 
        else if(!Input.GetButton("Walk") && !isRunningSound) 
        {
            Debug.Log("run");
            CancelInvoke(currentSound);
            currentSound = "RunSound";
            InvokeRepeating(currentSound, 0f, 0.3f);
            isRunningSound = true;
        } 
    }
    else
    {
        CancelInvoke(currentSound);
        
        isRunningSound = false;
    }
}

void RunSound() 
{
    audio.clip = audioRun;
    audio.Play();
}

void WalkSound() 
{
    audio.clip = audioWalk;
    audio.Play();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 06:22:24