I’m diving into the world of Mecanim (Unity 5.3.5f1) and it’s driving me nuts. As per title, how should I get current animation state, save it and then restore later? It seems like a simple task but it’s not when it comes to Mecanim (there’s no easy way to even get the name of the currently playing animation state!).
I’ve tried something like below, saving the current animation’s hash value and then trying to play it back later, but the saved hash value doesn’t match up with any of my animations and throws a warning instead?
private int savedHash;
private int hashStateIdle = Animator.StringToHash("Idle");
private int hashStateWalk = Animator.StringToHash("Walk");
void Start()
{
animator = GetComponent<Animator>();
}
void Save()
{
savedHash = animator.GetCurrentAnimatorStateInfo(0).GetHashCode();
}
void Restore()
{
if (animator.GetCurrentAnimatorStateInfo(0).GetHashCode() != savedHash)
animator.CrossFade(savedHash, 0.2f);
}
Sorry for the necro, but for anyone also looking into this in the future I thought I’d leave my solution here. Its probably not perfect, but I haven’t spotted a problem (yet)
struct State
{
public Vector3 Position;
public Quaternion Rotation;
public AnimatorStateInfo AnimatorState;
public AnimatorStateInfo AnimatorStateNext;
public AnimatorTransitionInfo AnimatorTransition;
}
State m_ReplayState;
public void RestoreState()
{
transform.position = m_ReplayState.Position;
Visuals.transform.rotation = m_ReplayState.Rotation;
Anim.Play( m_ReplayState.AnimatorState.shortNameHash, 0, m_ReplayState.AnimatorState.normalizedTime );
Anim.Update( 0f );
Anim.CrossFadeInFixedTime( m_ReplayState.AnimatorStateNext.shortNameHash, m_ReplayState.AnimatorTransition.duration, 0, 0f, m_ReplayState.AnimatorTransition.normalizedTime );
}
public void RecordState()
{
m_ReplayState.Position = transform.position;
m_ReplayState.Rotation = Visuals.transform.rotation;
m_ReplayState.AnimatorState = Anim.GetCurrentAnimatorStateInfo( 0 );
m_ReplayState.AnimatorStateNext = Anim.GetNextAnimatorStateInfo( 0 );
m_ReplayState.AnimatorTransition = Anim.GetAnimatorTransitionInfo( 0 );
}