[내일 배움 캠프 Unity 4기] W6D5 05.24 TIL

김용준·2024년 5월 24일
0

내일배움캠프

목록 보기
21/47

Goals

  • Practice the design pattern; FSM

Finite State Machine (FSM)

When the operation need to be separate with the state, the FSM pattern would be used. For example, the player character which is in the rest will be restore their health point per unit time. However, in the case of enemy encounter, the restoration was interupted and battle state will be invoked. Such a division of state in finite number can be written like following code snippet.

Player.cs
public class Player
{
  public PlayerState state;
  public float HP;
  
  public void Restoration()
  {
    if(this.state == PlayerState.Rest)
      HP += 5;
  }
}

public enum PlayerState
{
  Rest,
  Battle,
  Others
}
GameManager.cs
public class GameManager
{
  public void Battle(Player player)
  {
    switch(player.state)
    {
      case PlayerState.Rest:
      case PlayerState.Others:
        player.state = PlayerState.Battle;
        break;
      default:
        break;
    }
  }
}

The division using if / else if / else and switch / case could be written in finite number of cases. Among those commands, we can say the Finite State Machine, Which will be applied the state of object.

profile
꿈이큰개발자지망생

0개의 댓글