P
P
PRIYD2020-05-24 09:45:50
C++ / C#
PRIYD, 2020-05-24 09:45:50

Is it appropriate to use a coroutine here?

Hello.
Task: adding animation to the character when turning (pressing the A key - rotates by 90 *, pressing S - rotates by 180 *, pressing D - rotates by -90 *). After the turn animation has played (and the character turned accordingly), the state should return to the idle animation.
As I decided: I created a coroutine that waits 1 second and then returns the state to idle. The code:

bool isWPressed = Input.GetKey(KeyCode.W);
        
if ( (Input.GetKey(KeyCode.D)) && (!isWPressed) )
{
     animator.SetBool("isLeftTurn", true);
     yield return new WaitForSeconds(1f);
     animator.SetBool("isLeftTurn", false);
}
else if ( (Input.GetKey(KeyCode.A)) && (!isWPressed) )
{
     animator.SetBool("isRightTurn", true);
     yield return new WaitForSeconds(1f);
     animator.SetBool("isRightTurn", false);
}
else if ( (Input.GetKey(KeyCode.S)) && (!isWPressed) )
{
     animator.SetBool("isBackTurn", true);
     yield return new WaitForSeconds(1f);
     animator.SetBool("isBackTurn", false);
}


Screenshot of the animator:
5eca176d3cc54008185781.png

Problem: everything works, but something tells me that this is a crutch and can be done more correctly. What are the alternatives?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis Zagaevsky, 2020-05-24
@zagayevskiy

Surely this animator has a callback to end the animation. If not, I'll be surprised.

N
Nikita, 2020-05-25
@SKyRo

You can switch to turn state by trigger , and then Has Exit Time .
Docks: Animation Parameters ; Animator.SetTrigger

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question