Search Unity

How to play and reverse an animation.

Discussion in 'Scripting' started by Dude_Mojo, Sep 23, 2016.

  1. Dude_Mojo

    Dude_Mojo

    Joined:
    Jul 14, 2016
    Posts:
    13
    Hello Unity peeps I am a coding noob and im trying to find out how I can run an objects animation upon clicking on the object. I also am trying to find out how to reverse the same animation once I click on the object a second time. Thanks for any help you can give. I am coding in C# preferably.
     
  2. Magnumstar

    Magnumstar

    Joined:
    Oct 3, 2015
    Posts:
    304
    set the animation controller speed to -1
     
  3. Magnumstar

    Magnumstar

    Joined:
    Oct 3, 2015
    Posts:
    304
    Just read your question more thoroughly. To play the animation on click you need a button that is the child of a Canvas object, the canvas object needs a graphic raycaster compoennt, and you must have an Event System object in your scene.

    Once you do these things, you need to create a button from the components. The button has an area called OnClick() which will call a method in your hierarchy, so create your function somewhere to call when a button is clicked, then select it here.
     
  4. IsGreen

    IsGreen

    Joined:
    Jan 17, 2014
    Posts:
    206
    If you play animation with negative speed, you need to change animation position to finish using normalizedTime of AnimationState.

    You can use OnMouseDown event of MonoBehaviour class to detect mouse clicks on Mesh(Mesh need Collider component).

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. [RequireComponent(typeof(Collider)),RequireComponent(typeof(Animation))]
    5. public class AnimationControl : MonoBehaviour {
    6.  
    7.     public AnimationClip animationClip;
    8.  
    9.     float speed = -1f;
    10.     new Animation animation;
    11.  
    12.     // Use this for initialization
    13.     void Start () {
    14.         this.animation = this.GetComponent<Animation>();
    15.         if(this.animationClip == null)
    16.         {
    17.             Debug.Log(this.GetType().ToString() + ": Animation Clip needed");
    18.             Destroy(this);
    19.         }
    20.     }
    21.    
    22.  
    23.     //MonoBehaviour Event. Need Collider to work correctly
    24.     void OnMouseDown()
    25.     {
    26.         if (this.animation.isPlaying) return; //exit
    27.         this.speed = -this.speed;
    28.         this.animation[this.animationClip.name].speed = this.speed;
    29.         this.animation.Play(this.animationClip.name);
    30.         if (this.speed < 0f) this.animation[this.animationClip.name].normalizedTime = 1f;
    31.     }
    32. }
    Download link.
     
    Magnumstar likes this.