Thanks really useful, I am now starting to get my head around it.
The bit that hasn’t managed to sink in is if I was using a Finite State Machine it would manage the state but also have a switch statement that checks the state, changes the state and then actions some code based on the state.
I have a working state machine which transitions as expected but as I will be playing a forward, backward or stop sound the individual classes do not know about the audio. So to achieve this with the state machine as suggested sounds like the correct place to do it.
How does the state machine know which one without checking the state like it does with a switch statement in the finite state machine?
Am I being a bit thick / missing something?, here is my state machine.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Driver : MonoBehaviour, BinLorryContext
{
[SerializeField] float steeringSpeed = 0.1f;
[SerializeField] float lorrySpeed = 0.1f;
BinLorryState currentstate = new Stop();
void Update()
{
float steerAmount = Input.GetAxis("Horizontal") * steeringSpeed * Time.deltaTime;
float driveAmount = Input.GetAxis("Vertical") * lorrySpeed * Time.deltaTime;
if (driveAmount < 0)
{
steerAmount = -steerAmount;
Reverse();
}
else if (driveAmount > 0)
{
Forward();
} else
{
Brake();
}
transform.Translate(new Vector3(0, driveAmount, 0.0f));
transform.Rotate(new Vector3(0, 0, -steerAmount));
//Debug.Log(currentstate);
}
public void Forward() => currentstate.Forward(this);
public void Reverse() => currentstate.Reverse(this);
public void Brake() => currentstate.Brake(this);
void BinLorryContext.SetState(BinLorryState newstate)
{
currentstate = newstate;
}
}
public interface BinLorryContext
{
void SetState(BinLorryState newstate);
}
public interface BinLorryState
{
void Forward(BinLorryContext context);
void Reverse(BinLorryContext context);
void Brake(BinLorryContext context);
}
public class DriveForward : BinLorryState
{
public void Forward (BinLorryContext context)
{
Debug.Log(“Still Driving Forward”);
}
public void Reverse (BinLorryContext context)
{
context.SetState(new DriveReverse());
}
public void Brake(BinLorryContext context)
{
context.SetState(new Stop());
}
}
public class Stop : BinLorryState
{
public void Forward(BinLorryContext context)
{
context.SetState(new DriveForward());
}
public void Reverse(BinLorryContext context)
{
context.SetState(new DriveReverse());
}
public void Brake(BinLorryContext context)
{
Debug.Log("Still Parked");
}
}
public class DriveReverse : BinLorryState
{
public void Forward(BinLorryContext context)
{
context.SetState(new DriveForward());
}
public void Reverse(BinLorryContext context)
{
Debug.Log("Still Reversing");
}
public void Brake(BinLorryContext context)
{
context.SetState(new Stop());
}
}