Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Question Setting up a proper state machine

Discussion in '2D' started by indespairxx, Aug 1, 2020.

  1. indespairxx

    indespairxx

    Joined:
    Feb 7, 2020
    Posts:
    6
    Hi everyone after watching lots of youtube and googling about 10,000 things I'm a little confused on state machines. On the code below, I am unsure how to break out of states and go into other states when it comes to my movement script.

    If I initiate PlayerMovement() on my idle state to enable walking, it just switches to State.Moving then completely stops my character's ability to move.

    Code (CSharp):
    1.    
    2. protected virtual void Update()
    3.     {
    4.         IframeAnimation();
    5.         GatherMovementData();
    6.  
    7.         switch (state)
    8.         {
    9.             case State.Idle:
    10.                 break;
    11.  
    12.             case State.Moving:
    13.                 Dash();
    14.                 ActivateAttack();
    15.                 MovementAnimation();
    16.                 break;
    17.         }
    18.  
    19.     }
    Code (CSharp):
    1.     protected virtual void FixedUpdate()
    2.     {
    3.         switch (state)
    4.         {
    5.  
    6.             case State.Moving:
    7.             StartCoroutine(PlayerMovement());
    8.                 break;
    9.         }
    10.     }
    Code (CSharp):
    1.     private IEnumerator PlayerMovement()
    2.     {
    3.         state = State.Moving;
    4.  
    5.         if (isAlive && !Input.GetKey(KeyCode.Space) && knockedBack == false)
    6.         {
    7.             rb.MovePosition(rb.position + movement * moveSpeed * Time.fixedDeltaTime);
    8.         }
    9.  
    10.         if (!isAlive)
    11.             yield return new WaitForSeconds(0f);
    12.  
    13.        
    14.     }
     
  2. indespairxx

    indespairxx

    Joined:
    Feb 7, 2020
    Posts:
    6
  3. Lo-renzo

    Lo-renzo

    Joined:
    Apr 8, 2018
    Posts:
    1,323