I have an animation that is set to run once and at its end there is and AnimationEvent that causes the animation to load a new scene. The user can click a button that is meant to reverse the animation to certain positions.
However using Animator.SetTime(float time)
seems to always cause the animator to fast forward, warp to 0 and continue until the set time. Thus, it triggers all intermediate events. At least as of Unity 5.2, the animator seems to be threaded thus a hack like the following
public void setTime(int direction)
{
timeIndex = Mathf.Clamp(timeIndex + direction, 0, boardSwitchTimes.Length - 1);
if (anim)
{
switchingBoards = true;
anim.SetTime(boardSwitchTimes[timeIndex]);
switchingBoards = false;
}
}
won’t work as the switchingBoards = false
happens before the event at the end of the animation is triggered (by the anim.SetTime
). I verified this by logging the end of animation event and the last line of the setTime
function.
I have a solution, though I doubt it covers all cases and will work when building to all different sorts of platforms. All events checks the status of switchingBoards
and the end of animation event sets it back to false
if it was true
:
public void setTime(int direction)
{
timeIndex = Mathf.Clamp(timeIndex + direction, 0, boardSwitchTimes.Length - 1);
if (anim)
{
switchingBoards = true;
anim.SetTime(boardSwitchTimes[timeIndex]);
if (direction >= 0)
switchingBoards = false;
}
}
public void exampleNotEndOfAnimationEvent()
{
if (!switchingBoards)
{
// Do the stuff
}
}
public void exampleEndOfAnimationEvent()
{
if (!switchingBoards)
{
// Load new scene
}
switchingBoards = true;
}
This whole mess feels very uncertain and far from clear, so I wonder if there’s another better and intended way to get around the threading issue?
An obvious answer would be to just skip setting the time and breaking up the animation into many smaller animations and work with transitions. I’d rather not have such a setup.