A singleton is a special class that can only have one instance. Because of this, it’s super-easy to reference functions inside a singleton from another class. Singletons can talk to other singletons, and non-singleton classes can talk to singletons, but singletons can not talk to non-singleton classes.

Here’s an example were we use singletons to send debug messages, change a text box, and instantiate a prefab:

Without using singletons, we might try and access a ui component from a player script like this:

--

--

Ok, let’s build a Finite State Machine that will act as our smart AI. As our AI travels the waypoints, we want it to go into attack mode at each point. For now we’ll just have it stop for 3 seconds and then move on to the next waypoint. Like this:

All we need is an If statement in our Attack Switch Case that calls a coroutine and updates the switch:

--

--

Let’s take our previous example a step further… Suppose we want to change the color of our ai to match the change in speed when we press the space bar, like this:

Since we’ve already set up our custom class, we can easily add a material to our enum:

--

--

If we want to build an AI agent that can travel around a scene autonomously, we need a way to set the area and boundaries. We do this in Unity using a Navmesh:

Turn on the Navigation tab using the menu Windows — AI:

--

--