Sensors

Using the Mecanim state machine in this way is very powerful and just having scripts update the parameters of the state machine through input (user taps a key, or scene loads) is simple enough. However, if you want reactive AI, you might want to think about sensors.

Sensors are effectively the AI's eyes and ears and whatever else it wants to use to detect action within a scene (even if it's an alarm or trip wire). Generally, they are self-contained components that look after themselves and inform whatever they are attached to. They can be as complex or as simple as you need them to be.

A basic sensor might be an empty GameObject with a trigger collider (the trip wire), which tells the enemy state machine that the player has come into view. ...

Get Mastering Unity 2D Game Development - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.