How do I get an animation to play on a model when the model's transform is moving?

This may seem a bit obvious, but for the life of me, I can’t figure it out:

my movement system is sort of point-and-click based, where as if I click on the ground, the character (which is using a nav mesh agent) will move to that position which is created using a raycast.

Basically, what I want to do is create a boolean determining whether or not the character’s model transform is moving. If it is moving, then the boolean needs to be read by the animator controller’s condition which will display the walking animation so long as the model’s transform is moving. If not, then the controller will just play the idle animation.

(If you can, please respond in C#)

Add a little script that checks NavMeshAgent.velocity. Set the animator controller’s Boolean parameter true if it’s above a certain threshold:

public class NavAnimation : MonoBehaviour {
    void Update() {
        var moving = GetComponent<NavMeshAgent>().velocity.magnitude > 0.05f;
        GetComponent<Animator>().SetBool("Moving", moving);
    }
}

(I kept the code short for clarity; in practice, cache GetComponent(), check for null, etc.)

If your walking animation has root motion (i.e., translation on the Z-axis), you’ll probably want to set:

NavMeshAgent.updatePosition = false;

and let the animation move the transform.

You could also replace your Boolean Moving parameter with a float Speed parameter and turn your animator controller state into a blend tree. Blend between idle and walking. This future-proofs you in case you add a run animation in the future. Then you could blend something like this:

Speed=0: idle
Speed=1: walk
Speed=2: run

1 Like

I tried inputting what you gave me and It’s giving me an error on the velocity:

error CS0019: Operator >' cannot be applied to operands of type UnityEngine.Vector3’ and `float’

also, how exactly would I be able to cache the moving variable? through a bool or gameobject? (if that’s what I’m supposed to do)

Sorry, try velocity.magnitude. (I fixed the code above.)

I switched it and it works, thanks!

Happy to help!