Search Unity

How to keep an animation from going pass the last keyframe or going pass the first keyframe?

Discussion in 'Animation' started by strangeclouds30853, Jun 22, 2019.

  1. strangeclouds30853

    strangeclouds30853

    Joined:
    Jun 22, 2019
    Posts:
    4
    So I ran into an interesting problem today. I want to make a graphic slowly fade in whenever the user has the mouse over the object and slowly fade out once they move the mouse cursor off the object. For the most part I got the effect I wanted easily enough by using the animator and altering the alpha in the sprite renderer . However then I noticed a really big problem. The animation would take too long before playing if you leave the mouse on the object or off the object for too long, when it should be instantaneous.

    To give an example: If I leave my mouse cursor off the object for 10 seconds after the object is completely transparent, I would have to leave the mouse cursor on the object for 10 seconds before the "Fade In" effect would start and vice versa if I leave my mouse on the object for too long, the "Fade out" would be delayed. I theorized that unity's animation states does not stop and just keeps on going if it is not looped or exited. That is the only possible explanation for this that I can think of.

    So my question is: is there any way to stop the animation from going pass the last key or going pass the first key? The reason for this is to preserve the smooth transition from fading in to fading out instantly and vice versa. I don't want to duplicate the state and set the 2nd state's speed to -1 as that would cause the graphic to pop to full alpha before fading out if the user removes the cursor before it is fully faded in.

    Here is the script that I used.
    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class MouseOverZone : MonoBehaviour
    4. {
    5.     public Animator anim;
    6.  
    7.     public void OnMouseEnter()
    8.     {
    9.         anim.SetFloat("speed", 1.0f);
    10.         anim.SetBool("isMouseOver", true);
    11.     }
    12.  
    13.     public void OnMouseExit()
    14.     {
    15.         //set speed multiplier to negative to make the animation play backwards
    16.         anim.SetFloat("speed", -1.0f);
    17.     }
    18. }

    Screenshot of the animation window:


    For some reason I can't seem to upload the screenshot, but basically it's just has a blank state that transitions to the "Fade_In" state( alpha of the sprite increases from 0 to 1 over 2.5 seconds.) The "Fade_In" state does not exit to any where.