I make a runner, by pressing the mouse the character runs, when I release it stops, just by pressing the mouse the running animation turns on and off, but when the mouse is pressed the character runs, stops and continues to run.
In the video, when the cursor is on the game screen, I click on the mouse, when I moved the cursor away, I don’t click.
Code that moves character:
using UnityEngine;
public class StickmanMover : MonoBehaviour
{
[SerializeField] private float _maxSpeed;
[SerializeField] private float _speed;
private Rigidbody _rigidbody;
private void Start()
{
_rigidbody = GetComponent<Rigidbody>();
}
private void Update()
{
if (Input.GetKey(KeyCode.Mouse0) && _rigidbody.velocity.magnitude < _maxSpeed)
{
_rigidbody.AddForce(Vector3.forward * _speed * Time.deltaTime);
}
}
}
Code that changes animations:
using UnityEngine;
public class StickmanAnimator : MonoBehaviour
{
private Animator _animator;
private void Start()
{
_animator = GetComponent<Animator>();
}
private void Update()
{
if (Input.GetKey(KeyCode.Mouse0))
{
_animator.SetTrigger("Run");
}
else
{
_animator.SetTrigger("Idle");
}
}
}
>Solution :
Triggers can stack!
So what happens is basically you pile up a lot of triggers, one each frame and later they are all consumed by just as many transitions.
For your use case you rather want to use a single Boolean parameter – let’s say Running – and configure your transitions accordingly
Idle --Running == true--> Run
Run --Running == false--> Idle
and then do
private void Update()
{
_animator.SetBool("Running", Input.GetKey(KeyCode.Mouse0));
}
The alternative (not needed in your case but just for completion) would be to actively reset the triggers whenever entering a new state.
I described this further at the bottom of this post

