Search Unity

Question Unity animations loop with each other when transitioning

Discussion in 'Animation' started by Kujji, Mar 22, 2023.

  1. Kujji

    Kujji

    Joined:
    Oct 20, 2021
    Posts:
    109
    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:
    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class StickmanMover : MonoBehaviour
    4. {
    5. [SerializeField] private float _maxSpeed;
    6. [SerializeField] private float _speed;
    7.  
    8. private Rigidbody _rigidbody;
    9.  
    10. private void Start()
    11. {
    12.     _rigidbody = GetComponent<Rigidbody>();
    13. }
    14.  
    15. private void Update()
    16. {
    17.     if (Input.GetKey(KeyCode.Mouse0) && _rigidbody.velocity.magnitude < _maxSpeed)
    18.     {
    19.         _rigidbody.AddForce(Vector3.forward * _speed * Time.deltaTime);
    20.     }
    21. }
    22. }
    Code that changes animations:
    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class StickmanAnimator : MonoBehaviour
    4. {
    5. private Animator _animator;
    6.  
    7. private void Start()
    8. {
    9.     _animator = GetComponent<Animator>();
    10. }
    11.  
    12. private void Update()
    13. {
    14.     if (Input.GetKey(KeyCode.Mouse0))
    15.     {
    16.         _animator.SetTrigger("Run");
    17.     }
    18.     else
    19.     {
    20.         _animator.SetTrigger("Idle");
    21.     }
    22. }
    23. }
    Transition settings:

     
  2. Kujji

    Kujji

    Joined:
    Oct 20, 2021
    Posts:
    109
    I changed trigger on bool variable, and changed code in animations changer to:

    _animator.SetBool("Running", Input.GetKey(KeyCode.Mouse0));