Search Unity

Animation looping question

Discussion in 'Getting Started' started by MikeTeavee, Sep 8, 2015.

  1. MikeTeavee

    MikeTeavee

    Joined:
    May 22, 2015
    Posts:
    194
    In an FPS game I'm making, I set up an animation for gun-bob, and a script that enables the animation while walking forward (Holding 'W'). I've tried setting the animation's Wrap-Mode to Once or Loop.

    If I set it to 'Once', the animation goes 1 loop and stops until I press 'W' again. (not what I want).

    If I set Wrap-Mode to Loop, the animation loops infinitely even when releasing 'W'. (also not what i want!)

    Here's my code:

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class WalkingMovement : MonoBehaviour {
    5.     // Use this for initialization
    6.     void Start () {
    7.     }
    8.  
    9.     // Update is called once per frame
    10.     void Update () {
    11.     if (Input.GetKeyDown (KeyCode.W)) {
    12.             gameObject.GetComponent<Animation> ().Play ("WalkAnimation");
    13.         }
    14.     }
    15. }
    16.  
    Also, if it's useful, here is my animation in the Debug window...
     

    Attached Files:

  2. MikeTeavee

    MikeTeavee

    Joined:
    May 22, 2015
    Posts:
    194
    ...Solved the problem. After setting Wrap-Mode to Loop. The solution was to use GetKey() and not GetKeyDown()

    Also needed to add an Else-block and a Stop() call...

    Working code...
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class WalkingMovement : MonoBehaviour
    5. {
    6.     // Use this for initialization
    7.     void Start ()
    8.     {
    9.     }
    10.  
    11.     // Update is called once per frame
    12.     void Update ()
    13.     {
    14.         if (Input.GetKey (KeyCode.W)) {
    15.             //gameObject.GetComponent<Animation> ().wrapMode = WrapMode.Loop;
    16.             gameObject.GetComponent<Animation> ().Play ("WalkAnimation");
    17.         } else {
    18.             gameObject.GetComponent<Animation> ().Stop ("WalkAnimation");
    19.         }
    20.     }
    21. }
    22.  
     
    Last edited: Sep 8, 2015