viewers access
public class StateMachine<StateType, ContextType>
CyberPsychosis > StateMachine
StateMachines run one state at a time, allow for easy switchiung of states and controlled behaviour
| Name | Description |
|---|---|
|
Called when SwitchState<> is called on the statemachine |
MovementState.cs
using UnityEngine;
// Create a base type for the state machine, all states inherit from this class
public abstract class MovementState : State<Player>
{
// virtual utility method for movement behaviour
public virtual void OnMove(Vector2 InputDirection) { }
}
DefaultMovementState.cs
// Create a default state for the state machine
public class DefaultMovementState : MovementState
{
// Change the behaviour when moving
public override void OnMove(Vector2 InputDirection)
{
transform.position += new Vector3(InputDirection.x, 0, InputDirection.y) * Time.deltaTime;
}
}
Player.cs
using UnityEngine;
// Create a player class
public class Player : MonoBehaviour
{
// Create a new statemachine for MovementState, inherited from State<Player>
StateMachine<MovementState, Player> _movement = new StateMachine<MovementState, Player>();
private void Start()
{
// Default to the default movement state
_movement.SwitchState<DefaultMovementState>(this);
}
private void Update()
{
// Call the method of the active state, not of the inactive states.
_movement.state.OnMove(Input.MovementDirection);
}
}
| Name | Description |
|---|---|
|
Switch the state to the state of type T. T must derive of the type StateType |