Unity 2D enemy AI tutorial: make an enemy follow, patrol and chase the player in C# — detection radius, state switching and smooth movement.
▶ Full written tutorial (free): https://generalistprogrammer.com/tuto...
Unity 2D enemy AI, built from scratch — patrol, detection, chase, and a state machine to
tie them together. This Unity tutorial makes an enemy follow the player in 2D with correct,
current C# (Unity 2022+ / Unity 6). No NavMesh — this is pure 2D, the way most top-down and
platformer games actually handle enemy behavior.
A good enemy is really three behaviors, and this video builds each one:
Follow / chase — move the enemy toward the player with Vector2.MoveTowards, scaled by
speed times Time.deltaTime so it is frame-rate independent. Get the player from a serialized
Transform, or with GameObject.FindWithTag("Player").
Detection — a distance check with Vector2.Distance against a detectRange. Step inside the
range and the enemy notices you and gives chase; stay outside and it keeps patrolling. Plus a
note on Physics2D raycasts for real line-of-sight so it cannot see you through a wall.
Patrol — walk between waypoints held in a Transform array, advancing to the next point when
close, wrapping with modulo so the enemy loops the route forever.
The state machine — an enum State { Patrol, Chase } and a switch inside Update. Detection is
the switch that flips between states — the same clean pattern real games use for enemy AI.
Polish — flip the sprite toward movement with localScale, and add a stopping distance so the
enemy holds just short of the player instead of shoving into it and jittering.
Every line of C# is correct and compile-ready, taught through code walkthroughs and diagrams —
a detection-radius diagram and a Patrol / Chase state diagram. This is the exact Unity 2D enemy
AI skeleton real games build their enemies on, and it grows as you add Attack, Flee or Search.
Full written Unity enemy AI tutorial with copy-paste code, attack behavior and pathfinding:
https://generalistprogrammer.com/tuto...
The 30-day plan for beginners — Game Dev Starter Kit ($19):
https://generalistprogrammer.gumroad....
More beginner Unity builds:
https://generalistprogrammer.com/tuto...
— Chapters —
0:00 The 3 behaviors of enemy AI
0:15 Game Dev Starter Kit ($19)
0:39 3 behaviors + the state machine
1:59 Follow the player (Vector2.MoveTowards)
3:37 Detection radius (Vector2.Distance)
4:57 Patrol waypoints
6:07 The state machine (enum + switch)
7:35 Polish: flip sprite + stopping distance
8:43 Recap
9:26 Watch next + subscribe
#gamedev #unity #unity2d