Unity AI with Basic State Machine

September 24, 2019

Basic State Machine Setup

Unity Tutorial

Youtube – Unity3D AI with State Machine (FSM), Drones, and Lasers!

Tutorial #1

By: Unity3d College


Tutorial #1

This tutorial goes over a “good” version and a “bad” version of setting up state machines. The bad version will work, and is ok for very small scale projects and objects, but it does lack scalability and has some poor design choices going on.

The real state machine covered in this tutorial is not a monobehaviour, but is still able to access components of objects. This was a point they wanted to make sure they covered with the laser object reference.

To start going over the state machine, they go through the Drone class and its variables. Target is a public Transform but has a private setter. The Team variable Team uses an expression body property to allow the setting of team from the inspector without letting anything else change it.

The next class they go over is the StateMachine class. This starts with a dictionary that contains all of the possible states. It takes in a Type and a BaseState value. The Type is just type of the state class, and the BaseState is a new object of that specific state.

The Update method of StateMachine first checks if there’s a current state. If there is none, it sets a default state. It then performs a method called Tick to determine what the next state is (if it is either the same state again, or a new state). It then checks if the nextState is a different state, and if so, switches to the new state.

Each state has had its own class created, each of which inherits from a public abstract class called BaseState. None of these are monobehaviours, but you can still pass in a GameObject object through any state which gets set to a GameObject variable in the BaseState so the states know which object to control. This BaseState also uses protected variables so that classes that inherit from it may use them, without allowing anything else to access them. And finally, BaseState has a public abstract Type Tick method just to make sure every state class has a Tick method (actions to have an object perform in this state).

While checking through the individual state classes, they mentioned the use of nullables. You can add a “?” to the end of a variable declaration to make it nullable. This allows you to set that variable to null when you normally cannot. They like to do this just as a consistent way to help them check if something actually has had a value assigned to it or not.
Example:
private Vector3? _destination;

They also setup a GameSettings class to help them change general variables that go along with their state machine. This uses a simple singleton pattern setup like the following example:

public static GameSettings Instance { get; private set; }

private void Awake() {
if (Instance != null}
Destroy(gameObject);
else
Instance = this;
}