Unity中用C#脚本修改Animator变量及解决动画触发异常问题
Hey there! Let's fix your animation issues step by step and get that Idle/Walk/Run cycle working exactly how you want it.
First, Diagnose the Core Problem
Looking at your Update code, two key issues are causing the unwanted walking animation:
- You’re setting the Animator’s
Speedparameter to your fixedspeedvariable before checking input — so even when you’re not pressing WASD, you’re feeding a non-zero value to the Animator. - You’re passing the fixed movement speed instead of the actual current movement magnitude based on player input — the Animator’s
Speedparameter should reflect whether the player is moving, not just your default movement speed.
Fix the Code & Implement Idle/Walk/Run
Here’s a revised script with explanations:
using UnityEngine; public class PlayerMovement : MonoBehaviour { [Header("Movement Settings")] public float walkSpeed = 3f; public float runSpeed = 6f; private Animator animator; private float currentSpeed; void Start() { // Grab the Animator component attached to your player animator = GetComponent<Animator>(); // Start with walk speed by default currentSpeed = walkSpeed; } void Update() { // 1. Get player input first float horizontal = Input.GetAxis("Horizontal"); float vertical = Input.GetAxis("Vertical"); // 2. Toggle run with Shift if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)) { currentSpeed = runSpeed; } else { currentSpeed = walkSpeed; } // 3. Calculate movement direction and move the player Vector3 moveDirection = new Vector3(horizontal, 0f, vertical).normalized; transform.Translate(moveDirection * currentSpeed * Time.deltaTime); // 4. Set the Animator's Speed parameter based on actual movement float animatorSpeed = moveDirection.magnitude * currentSpeed; animator.SetFloat("Speed", animatorSpeed); } }
Key Changes Explained:
- Input first, then Animator update: We now check input before updating the Animator, so we only send a non-zero value when the player is actually moving.
moveDirection.normalized: Ensures consistent movement speed regardless of diagonal input.animatorSpeedcalculation: Combines input magnitude (0 when idle, 1 when moving) with current walk/run speed — this gives the Animator a clear value to trigger the right animation.- Shift run toggle: Switches between walk and run speed seamlessly.
Set Up Your Animator Controller Correctly
Make sure your transitions match these conditions to avoid jitter:
- Idle → Walk: Transition condition:
Speed > 0.1(use a small threshold instead of 0 to ignore tiny input noise) - Walk → Idle: Transition condition:
Speed <= 0.1 - Walk → Run: Transition condition:
Speed >= runSpeed - 0.5(adjust the threshold to match yourrunSpeedvalue) - Run → Walk: Transition condition:
Speed < runSpeed - 0.5 - Enable Has Exit Time for smooth animation blending, or disable it for instant state switches (adjust based on your game’s feel).
How to Modify Animator Variables with C# Scripts
Here are the most common methods to control Animator parameters, with examples:
- Float parameters: Use
animator.SetFloat("ParameterName", value);(like we did withSpeed). For better performance, precompute a hash:private int speedHash = Animator.StringToHash("Speed"); // Then use: animator.SetFloat(speedHash, animatorSpeed); - Bool parameters: Use
animator.SetBool("IsRunning", true/false);— perfect for toggle states like "is jumping" or "is crouching". - Integer parameters: Use
animator.SetInteger("WeaponType", 2);— useful for switching between multiple states (e.g., different weapons). - Trigger parameters: Use
animator.SetTrigger("Attack");— triggers a one-time animation (resets automatically after the transition).
Troubleshooting Your Previous Attempts
- Checking "Parameter" on animation clips: That’s for adding animation curves that modify parameters during an animation, not for controlling transitions between animations — so that wasn’t the right fix here.
- Using
Mathf.Abs(speed): This only makes the speed positive, but since you were passing the fixedspeedvariable instead of input-based movement, it didn’t solve the idle issue.
内容的提问来源于stack exchange,提问作者Philip Ch.
相关产品推荐
相关产品推荐

