Unity slider controlling animation

Tim Hanson

I'd like to create a slider that displays the current frame of an animation within unity, and when you move the slider it updates the current frame within the animation.

So far I have (edited code)

using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class NewAnimController : MonoBehaviour {


public Slider sliderScrubber;
public Animator animator;


void Start()
{
    float t = animator
    .GetCurrentAnimatorStateInfo(0)
    .normalizedTime;


    //animator.speed = 0.0001f;
    //slider.onValueChanged.AddListener(OnValueChanged);
}

public void Update()
{
    float animationTime = animator.GetCurrentAnimatorStateInfo(0).normalizedTime;
    Debug.Log("animationTime (normalized) is " + animationTime);
    sliderScrubber.value = animationTime;
}

public void OnValueChanged(float changedValue)
{
    animator.speed = 0.0001f;
    animator.Play("Take 001", -1, sliderScrubber.normalizedValue);
}
}

At the moment this changes the current frame in the animation when you adjust the slider, but when the animation is played, the slider doesn't update.

How can I get this to work in both directions?

Many thanks

Fattie

First be sure to delete all code lines

animation.speed = 0.0001f

which appear to be leftover from a tutorial or debugging.


What about

public void Update()
 {
 float animationTime = animator.GetCurrentAnimatorStateInfo(0).normalizedTime;
 // in case of a looping anime, animationTime = animationTime %1f;

 Debug.Log("animationTime is " + animationTime);
 // of course remove that in production

 slider.value = animationTime;
 }

Note of course set the scrubber min/max to 0f, 1f in the editor.

Note, you may prefer to make a "scrubber" for a joint position; also works nice.

Note, subtle issue: experienced programmers may prefer to set the animation speed to zero, while the user's finger is holding down the slider; probably OK without doing this.


NOTE take care to delete all references to animation.speed. It apears to be a carry-over from an incorrect tutorial.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

TOP Ranking

HotTag

Archive