Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unity animations loop with each other when transitioning

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.

Video of problem

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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");
    }
}
}

Transitions settings:
enter image description here
enter image description here

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading