Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

C# Animation Loops Badly

Discussion in 'Scripting' started by LandonF, Mar 1, 2016.

  1. LandonF

    LandonF

    Joined:
    Mar 1, 2016
    Posts:
    34
    Hello. When I use my code, the animation gets stuck and keeps looping at the first frame while holding the up key. Doesn't even play all the way through. Help?
    Code (CSharp):
    1.  
    2. void Update ()
    3.     {
    4.         //Move Controls
    5.         if (Input.GetKey("left"))
    6.         {
    7.             transform.Rotate(0, -30 * speed * Time.deltaTime, 0);
    8.          }
    9.  
    10.          if (Input.GetKey("right"))
    11.            {
    12.                transform.Rotate(0, 30 * speed * Time.deltaTime, 0);
    13.            }
    14.  
    15.              if (Input.GetKey("up"))
    16.              {
    17.                transform.Translate(Vector3.forward * speed * Time.deltaTime);
    18.                anim.Play("Walk", -1, 0f);
    19.              }
    20.  
    21.                 if (Input.GetKey("down"))
    22.                 {
    23.                     transform.Translate(Vector3.back * speed * Time.deltaTime);
    24.                 }
     
  2. bdev

    bdev

    Joined:
    Jan 4, 2011
    Posts:
    656
    try changing it to
    Code (csharp):
    1.  
    2. anim.Play("Walk",-1,float.NegativeInfinity);
    3.  
     
  3. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,848
    Well, on every frame while the up key is held, you tell the animation to play. You think "play" means "start this animation, or continue it if it's already started," but it doesn't. It means "start this animation from the beginning." So if that's not what you want, Don't Do That. :)

    One possible fix would be to have a separate check for Input.GetKeyDown("up"), and play the animation there (i.e. only when the key is initially pressed).
     
    LandonF likes this.
  4. LandonF

    LandonF

    Joined:
    Mar 1, 2016
    Posts:
    34
    Sorry for not replying for almost a month. But I used your idea of GetKeyDown when I saw your reply a few weeks ago and it worked! Thank you. Much appreciated.
     
    JoeStrout likes this.