---
# System prepended metadata

title: Unity Platform 12 State Machine
tags: [platform]

---

Unity Platform 12 State Machine
===
2020.08.24

###### tags: `platform`

## List
1. [Module Split](#MS)
2. [State](#S)
3. [State Machine](#SM)
4. [Entity](#E)

## Content
### Module Split<a id="MS"/>
State is Obj's state.<br>Like react state, each state has their logic<br>State Machine controls states.
```=
Entity              : Work Main Logic(Monobehavior)

FiniteStateMachine  : control State

State               : State Enter & Update(logic, physics) & Exit action
-> inherit
    |---IdleState
    |---MoveState

Data                : ScriptingObject, State attribute Data
-> inherit
    |---D_Entity
    |---D_IdleState
    |---D_MoveState
```

### State<a id="S"/>
State is objs state logic.<br>Normally, set animation and physics & logic<br>All states have enter and exit.
```csharp=
public class State
{
    protected FiniteStateMachine stateMachine;
    protected Entity entity;

    protected float startTime;
    protected string animBoolName;

    public State(Entity entity, FiniteStateMachine stateMachine, string animBoolName)
    {
        this.entity = entity;
        this.stateMachine = stateMachine;
        this.animBoolName = animBoolName;
    }

    public virtual void Enter()
    {
        startTime = Time.time;
        entity.anim.SetBool(animBoolName, true);
    }

    public virtual void Exit()
    {
        entity.anim.SetBool(animBoolName, false);
    }

    public virtual void LogicUpdate()
    {

    } 

    public virtual void PhysicsUpdate()
    {

    }
}
```

### State Machine<a id="SM"/>
State Machine controls state changing.
```csharp=
public class FiniteStateMachine
{
    public State currentState { get; private set; }

    public void initialize(State startingState)
    {
        currentState = startingState;
        currentState.Enter(); //initialize
    }

    public void ChangeState(State newState)
    {
        currentState.Exit();
        currentState = newState;
        currentState.Enter();
    }
}
```

### Entity<a id="E"/>
Entity is main script<br>Set real movement and action in game.
```csharp=
public class Entity : MonoBehaviour
{
    public FiniteStateMachine stateMachine;
    public D_Entity entityData;

    public Rigidbody2D rb { get; private set; }
    public Animator anim { get; private set; }
    public GameObject aliveGameObject { get; private set; }

    public virtual void Start()
    {
        aliveGameObject = transform.Find("Alive").gameObject;
        rb = aliveGameObject.GetComponent<Rigidbody2D>();
        anim = aliveGameObject.GetComponent<Animator>();
        stateMachine = new FiniteStateMachine();
    }

    public virtual void Update()
    {
        stateMachine.currentState.LogicUpdate();
    }

    public virtual void FixedUpdate()
    {
        stateMachine.currentState.PhysicsUpdate();
    }

    public virtual void OnDrawGizmos() {
        
    }
}
```
