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.