unity animation.play() doesn't work

41,921

Solution 1

From the manual:

Play() will start animation with name animation, or play the default animation. The animation will be played abruptly without any blending.

Since you call this every frame, I'd suppose it will just show the first frame of the animation and then be stopped by the next animation.Play in the next Update. Try this:

if (!animation.isPlaying) {
    animation.Play();
}

In general, I would suggest using Mechanim for character animations.

Solution 2

Another viable option along with the solution above is CrossFadeQueued.

You just simply use the function below and it'll seamlessly CrossFade.

usage is PlayAnimation("mcrunsw");

function PlayAnimation(AnimName : String) {
    if (!animation.IsPlaying(AnimName))
        animation.CrossFadeQueued(AnimName, 0.3, QueueMode.PlayNow);
}
Share:
41,921
Ozgur Yalcin
Author by

Ozgur Yalcin

Updated on April 04, 2020

Comments

  • Ozgur Yalcin
    Ozgur Yalcin over 3 years

    i have a simple script that should animate my player but its not working. i read forums for a while, some had issues about animation legacy option and i fixed it, but my character still doesn't animate, and there isn't any compiling errors. Here is my script:

    using UnityEngine;
    using System.Collections;
    
    public class maincharacter : MonoBehaviour {
    
        void Start () {
        }
    
        float xSpeed = 10f;
        float zSpeed = 10f;
        public float playerMovementSpeed = 10f;
    
        void Update () {
           float deltaX = Input.GetAxis ("Horizontal") * xSpeed;
           float deltaZ = Input.GetAxis ("Vertical") * zSpeed;
    
           Vector3 trans = new Vector3 (deltaX + deltaZ ,0f,deltaZ - deltaX);
           transform.Translate (trans.normalized * Time.deltaTime * playerMovementSpeed, Space.World);
    
           animation.Play ("mcrunsw");
    
           /*if (deltaX != 0 || deltaZ != 0) {
                     animation.Play ("mcrunsw");
              }*/
        }
    }
    

    Here is my gameObject and animation: enter image description here

    Any help would be appreciated. Thanks in advance.

  • Ozgur Yalcin
    Ozgur Yalcin over 9 years
    Using Mechanim did the work, plus its easier to use with multiple animations and states. Thanks a lot.