EloiStree / HelloSharpForUnity3D

Here we are going to check all the basic need to work in Unity3D with C#
0 stars 0 forks source link

Pattern: State #117

Open EloiStree opened 4 months ago

EloiStree commented 4 months ago

https://refactoring.guru/design-patterns/state https://en.wikipedia.org/wiki/State_pattern https://youtu.be/tv-_1er1mWI?t=599

https://gameprogrammingpatterns.com/state.html

EloiStree commented 4 months ago

D

EloiStree commented 4 months ago

With Enum

public enum PlayerControllerState
{
 Idle,
 Walk,
 Jump
}
public class UnrefactoredPlayerController : MonoBehaviour
{
 private PlayerControllerState state;
 private void Update()
 {
 GetInput();
 switch (state)
 {
 case PlayerControllerState.Idle:
 Idle();
 break;
 case PlayerControllerState.Walk:
 Walk();
 break;
 case PlayerControllerState.Jump:
 Jump();
 break;
 }
 }
 private void GetInput()
 {
 // process walk and jump controls
 }
 private void Walk()
 {
 // walk logic
 }
 private void Idle()
 {
 // idle logic
 }
 private void Jump()
 {
 // jump logic
 }
}
EloiStree commented 4 months ago

With state

public interface IState
{
 public void Enter()
 {
 // code that runs when we first enter the state
 }
 public void Update()
 {
 // per-frame logic, include condition to transition to a new
state
 }
 public void Exit()
 {
 // code that runs when we exit the state
 }
}

[Serializable]
public class StateMachine
{
 public IState CurrentState { get; private set; }
 public WalkState walkState;
 public JumpState jumpState;
 public IdleState idleState;
 public void Initialize(IState startingState)
 {
 CurrentState = startingState;
 startingState.Enter();
 }
 public void TransitionTo(IState nextState)
 {
 CurrentState.Exit();
 CurrentState = nextState;
 nextState.Enter();
 }
 public void Update()
 {
 if (CurrentState != null)
 {
 CurrentState.Update();
 }
 }
}