Stealth games, tower defense and survival shooters all need enemies that can see. Not “the player is within 10 metres” see, but “the player is in front of me, close enough, and nothing is in the way” see. This guide builds Unity enemy line of sight with a field of view cone: a distance check, an angle check, a raycast that respects walls, a detection meter that fills over time and gizmos so you can see the cone in the Scene view.
The Three Checks
An enemy can see a target only if all three of these pass, tested cheapest first:
- Range: is the target closer than the view distance?
- Angle: is the target inside the view cone in front of the enemy?
- Line of sight: does a ray from the enemy’s eyes to the target reach it without hitting a wall first?
Ordering matters for performance. Range and angle are a few multiplications. A raycast is more expensive, so only cast it when the first two pass. With a handful of enemies this is trivial, but it adds up with a crowd. The raycast tutorial explains the Physics.Raycast parameters used below.
The Vision Script
Add this to your enemy. Assign the player’s transform and set the masks in the Inspector.
using UnityEngine;
public class EnemyVision : MonoBehaviour
{
[SerializeField] Transform target;
[SerializeField] Transform eyes; // empty child at head height
[SerializeField] float viewDistance = 12f;
[SerializeField, Range(1f, 360f)] float viewAngle = 90f;
[SerializeField] LayerMask obstacleMask; // walls, props, anything that blocks sight
[SerializeField] LayerMask targetMask; // the layer the player is on
public bool CanSeeTarget { get; private set; }
void Update()
{
CanSeeTarget = CheckSight();
}
bool CheckSight()
{
if (target == null) return false;
Vector3 origin = eyes != null ? eyes.position : transform.position;
Vector3 toTarget = target.position - origin;
float distance = toTarget.magnitude;
// 1. range
if (distance > viewDistance) return false;
// 2. angle (flatten to the ground plane so looking up or down does not matter)
Vector3 flat = new Vector3(toTarget.x, 0f, toTarget.z);
if (flat.sqrMagnitude > 0.0001f)
{
float angle = Vector3.Angle(transform.forward, flat);
if (angle > viewAngle * 0.5f) return false;
}
// 3. line of sight
int mask = obstacleMask.value | targetMask.value;
if (Physics.Raycast(origin, toTarget.normalized, out RaycastHit hit, viewDistance, mask,
QueryTriggerInteraction.Ignore))
{
return ((1 << hit.collider.gameObject.layer) & targetMask.value) != 0;
}
return false;
}
}
The angle is the full cone width, so viewAngle = 90 means 45 degrees either side of forward. That is why the code compares against half. The raycast mask includes both obstacles and the target. If the first thing the ray hits is on the target layer, the enemy sees it. If it hits a wall first, the wall is returned and the check fails.
Layers and Eye Height
Two small setup details cause most line of sight bugs.
- Put the player on its own layer (for example “Player”) and add it to Target Mask. Put walls and cover on a layer like “Obstacle” or “Default” and add that to Obstacle Mask. Do not put the enemy’s own layer in either mask, or the ray hits the enemy’s own collider.
- Cast from eye height, not the feet. A ray from the enemy’s pivot (usually on the ground) to the player’s pivot (also on the ground) skims along the floor and hits every small bump and step. Create an empty child on the enemy at head height and assign it to Eyes. For the target, aim at a point near the chest. If your player pivot is at its feet, use
target.position + Vector3.up * 1fin the code instead oftarget.position.
Make sure the player has a collider, since the ray can only hit colliders. Triggers are ignored here on purpose, so a pickup zone in front of a wall does not block sight.
Drawing the View Cone
You cannot tune what you cannot see. Add gizmos to the same class so the cone shows in the Scene view when the enemy is selected:
void OnDrawGizmosSelected()
{
Vector3 origin = eyes != null ? eyes.position : transform.position;
Gizmos.color = Color.yellow;
Vector3 left = Quaternion.Euler(0f, -viewAngle * 0.5f, 0f) * transform.forward;
Vector3 right = Quaternion.Euler(0f, viewAngle * 0.5f, 0f) * transform.forward;
Gizmos.DrawLine(origin, origin + left * viewDistance);
Gizmos.DrawLine(origin, origin + right * viewDistance);
Gizmos.DrawWireSphere(origin, viewDistance);
if (target != null)
{
Gizmos.color = CanSeeTarget ? Color.green : Color.red;
Gizmos.DrawLine(origin, target.position);
}
}
The two yellow lines are the edges of the cone, the wire sphere shows the range, and a line to the target turns green when it is seen and red when it is not. Gizmos are editor-only and cost nothing in a build. Watch the red and green line while you walk behind a wall in Play mode. If it stays green through a wall, your masks are wrong.
A Detection Meter
Instant detection feels unfair. Most stealth games fill an awareness meter while the player is visible and drain it when they are not. Add this to the same script:
[Header("Detection")]
[SerializeField] float detectTime = 1.5f; // seconds in view to fully notice
[SerializeField] float forgetTime = 3f; // seconds to fully calm down
[SerializeField] float closeRange = 3f; // inside this, notice twice as fast
public float Awareness { get; private set; } // 0 to 1
public bool HasDetected => Awareness >= 1f;
void LateUpdate()
{
if (CanSeeTarget)
{
float speed = 1f / detectTime;
float dist = Vector3.Distance(transform.position, target.position);
if (dist < closeRange) speed *= 2f;
Awareness += speed * Time.deltaTime;
}
else
{
Awareness -= Time.deltaTime / forgetTime;
}
Awareness = Mathf.Clamp01(Awareness);
}
Because Update runs before LateUpdate, CanSeeTarget is always fresh when the meter reads it. Show the value with a small UI image above the enemy: set Image.fillAmount = vision.Awareness, and tint it yellow while filling and red at 1. The health bar tutorial has a world-space bar setup you can reuse for this.
Hooking It Into AI
Vision only reports facts. Your AI decides what to do with them. With the state machine from the enemy AI guide, a typical mapping is:
- Patrol: walking between points,
Awarenessnear 0. See the patrol waypoints guide. - Suspicious:
Awarenessabove about 0.3. Stop and turn toward the last known position. - Chase:
HasDetectedis true. Run at the target. - Search: the target is lost. Go to the last place it was seen, wait, then return to patrol.
Store the target’s position every frame CanSeeTarget is true. That “last known position” is what makes enemies feel smart, because they check where you were instead of knowing where you are. Keep a chasing enemy’s awareness from draining instantly, or it will give up the moment you duck behind a crate. A short memory timer helps.
For many targets (for example enemies spotting several player units), use Physics.OverlapSphere with the target mask to find candidates inside range, then run the angle and raycast checks on each. Use OverlapSphereNonAlloc or the buffered overload to avoid garbage, as covered in the GC guide.
🔧 Save time on AI
Behaviour tree, perception and pathfinding assets can replace a lot of this boilerplate. See our recommended Asset Store tools.
Troubleshooting
Enemy sees the player through walls
The wall’s layer is not in Obstacle Mask, or the wall has no collider. Check the layer on the wall object and confirm it has a Collider.
Enemy never sees the player
The player’s layer is missing from Target Mask, the player has no collider, or the Eyes object is inside a collider. Look at the gizmo line: if it is red at close range with a clear view, one of those is the cause.
Raycast hits the enemy itself
The enemy’s own layer is in a mask, or the eyes sit inside the enemy’s collider. Keep the enemy layer out of both masks, or move the eyes slightly forward of the collider.
The cone points the wrong way
The script uses transform.forward. If your model faces another axis because of how it was imported, rotate the model under an empty parent so the parent’s blue Z arrow points where the enemy looks.
Enemy sees the player when standing just behind it
The angle check was skipped or viewAngle is 360. Remember the value is the full width, and values near 360 see everything.
Detection is slow or jumpy on some machines
Per-frame raycasts on lots of enemies add up. Run the check every 0.1 to 0.2 seconds in a coroutine or timer instead of every frame, and stagger the start times so enemies do not all cast on the same frame.
FAQ
Does this work in 2D?
Yes, with changes. Use Physics2D.Raycast, a Vector2 direction, and Vector2.Angle against the direction the enemy faces (often transform.right or a facing variable). The three checks are the same.
How do I let the player hide in grass or darkness?
Multiply the awareness speed by a visibility factor. A trigger zone on the player can set a value like 0.3, so enemies fill the meter more slowly when the player is crouched in cover.
Should I raycast to one point or several?
One point is fine for most games. If a player can peek with just a head or foot visible and you want that to count, cast to two or three points (head, chest, feet) and treat any clear ray as seen.
Can enemies hear the player too?
Yes, and it is usually simpler. Have noisy actions call a method on nearby enemies with a position and loudness, and add to Awareness or send the enemy to investigate that spot.
Why use a raycast at all, instead of just range and angle?
Without it, enemies see through walls, floors and other rooms. The raycast is what makes cover work.
Reader questions
Asked by readers of this article and answered by AI. Behavior can differ between Unity versions, so test in yours.




Leave a Reply