1
\$\begingroup\$

What is the best way to suspend user interaction during an animation in Unity? Is there any standard technique that good games use.

E.g. In case of a card game, I am trying to flip a card. But if I click on the card in quick succession, it messes up the game.

Thanks!

\$\endgroup\$
  • 1
    \$\begingroup\$ I'm not sure about anything Unity specific, but you can set your code up so that clicking on a card only generates a response when there is no animation in progress. All you would need is an animation_in_progress Boolean, and to tell your user input code to only register clicks when that Boolean is negative. \$\endgroup\$ – GoldenGremlin Oct 5 '17 at 16:23
  • \$\begingroup\$ The Unity Animation system has an event system. You can put an event at the start and end of the animation clip and use the event receivers to disable and enable movement. \$\endgroup\$ – Yatoniea Oct 7 '17 at 17:45
2
\$\begingroup\$

If you are using an Animator controller, then I imagine you could so something similar to Hamza Hasan's answer in this other question. Set up two states, one idle, when you accept user input, and one animating. Transition to the animation when you set a trigger, let's say FlipCard. Transition back to idle automatically when the animation finishes. Now your code will look something like this, modified from Hamza Hasan's answer:

public Animator anim;

//condition for whether input is allowed
bool canFlip = true;

void OnMouseDown() {
    if (canFlip) {
        canFlip = false;
        anim.SetTrigger("FlipCard");
        //call coroutine which will handle resetting the state after
        StartCoroutine("FinishAnimation");
    }
}

//a coroutine. Will keep coming back to continue this code without
//blocking other code.
IEnumerator FinishAnimation() {
    //waits at this loop while the animation is still running
    while(anim.GetCurrentAnimatorStateInfo(0).normalizedTime < 1.0f) {
        yield return null;
    }
    //if we get here, the animation is complete
    canFlip = true;
}
| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.