VisionFieldMesh is a modular field-of-view (FOV) system for Unity. It combines a procedural vision mesh that is hidden behind obstacles with a matching target detector that checks line of sight and raises events when a target enters or leaves the field.
It supports six vision shapes, is configured entirely in the Inspector, and previews in the Scene view outside Play Mode. Use it for enemies, turrets, NPCs, guards, and other AI perception.
| Shape | Class | Preview |
|---|---|---|
| Circle / Sector | CircleShape |
![]() |
| Arrow | ArrowShape |
![]() |
| Half Ellipse | HalfEllipseShape |
![]() |
| Offset Triangle | OffsetTriangleShape |
![]() |
| Square | RectangleShape |
![]() |
| Rhombus | RhombusShape |
![]() |
- One shape, drawn and detected the same way: six shapes, each described once and shared by the mesh, the detector and the GPU pass.
- Cheap detection: shape formula plus up to three line-of-sight rays, 10 times a second; the nearest visible target wins; optional height limits.
- GPU occlusion: walls hide the field per pixel; the mesh never changes, and 50 cones cost about 0.9 ms CPU and 0.16 ms GPU per frame in the Editor.
- Shader effects: soft edges at walls, an outline glow and waves travelling outwards from the observer.
- Events:
OnTargetDetectedandOnTargetLostfire only when the visible target changes. - Editor preview and gizmos: the mesh updates as you edit the shape; gizmos show the outline, clip rays and the current target.
- Extensible: a new shape is one
VisionShapeclass and a prefab.
Compared with the first version of the project:
| Area | Before | Now |
|---|---|---|
| Engine | Unity 2022.3 | Unity 6000.5.3f1, URP 17.5 |
| Shapes | A mesh class and a detector class per shape, each with its own math | One VisionShape per prefab, shared by the mesh, the detector and the GPU pass |
| Walls | Mesh vertices clipped by raycasts every frame | Static mesh; walls hidden per pixel on the GPU (raycast clipping kept as a fallback) |
| Detection | Separate per-shape checks | Shape formula + up to 3 line-of-sight rays, 10 times a second, nearest target wins |
| Look | Toony Colors material | VisionField/Cone shader: soft wall edges, outline glow, waves |
| Tests | None | 225 EditMode and PlayMode tests, including GPU-vs-physics and rendered-pixel checks |
| Tooling | — | AI Unity Pipeline rules and skills, Unity CLI and MCP |
Bugs fixed along the way: level restart and path handling, HUD speed parsing (1.5 and 1,5), weapon states that kept running after the target was lost or the object was destroyed, shapes cut short at their corners and arc tops, and Unity 6.5 console errors in third-party plugins.
Each vision prefab carries one shape and two components that read it:
flowchart LR
subgraph Prefab["Vision prefab (Resources/VisionCone)"]
Field["VisionField<br/>the shape"]
Mesh["VisionFieldMesh<br/>draws the field"]
Detector["VisionFieldDetector<br/>finds targets"]
Field --> Mesh
Field --> Detector
end
Obstacles[("Obstacle layer")]
Targets[("Target layer")]
Occlusion["VisionOcclusion<br/>(GPU, all cones)"]
Occlusion -- "wall cross-section at eye height" --> Obstacles
Occlusion -- "polar distance atlas" --> Mesh
Detector -- "OverlapSphere + shape formula" --> Targets
Detector -- "line-of-sight raycast" --> Obstacles
Detector -- "OnTargetDetected / OnTargetLost" --> VisionAI
VisionAI --> WeaponAI["WeaponAI<br/>aim → shoot → idle"]
VisionFieldholds the shape: its outline, its reach and aContains(point)formula. Tests check that the formula and the drawn outline agree.VisionFieldMeshdraws a static triangle fan from the shape's centre to its outline with theVisionField/Coneshader.Gpumode (default) hides walls per pixel;CpuRaycastsis a fallback that clips the vertices.VisionFieldDetectorfinds candidates with one overlap query, keeps those inside the shape and casts line-of-sight rays only for them. 50 observers watching 50 enemies cost about 0.3 ms per pass.VisionOcclusiondoes the GPU work once per frame for up to 64 cones. Low boxes below eye height and roofs above it don't block, exactly like a horizontal raycast:
flowchart LR
Colliders[("Obstacle colliders<br/>around the cones")]
Slice["1. Slice pass<br/>wall cross-section at eye height<br/>→ 1024² top-down mask"]
Polar["2. Polar pass<br/>distance to the first wall<br/>→ 512 angles × 64 cones atlas"]
Cone["3. Cone shader<br/>hides pixels behind walls,<br/>edge glow and waves"]
Colliders --> Slice --> Polar --> Cone
Limits. One cross-section is shared by all cones (at their average eye height), so cones on very different floors share it. The mask covers up to 256 m; more spread-out cones get a coarser mask. Up to 64 cones are occluded; more are drawn without occlusion and a warning is logged. Trigger colliders are ignored. The passes need shader model 4.5: DX11/12, Vulkan, Metal, GLES 3.1+.
- Open the project in Unity 6000.5.3f1.
- Open
Assets/Scenes/Boot.unityand enter Play Mode. The boot scene loadsGame.unityautomatically. - In the HUD, choose a vision shape, enter a movement speed (units per second) and press Start. Pressing it again restarts the level with the selected shape.
- The player follows the level path. When an enemy enters the field, the turret aims and fires.
- Create a GameObject (it looks along its forward axis) and add
VisionFieldMesh— it addsVisionField,MeshFilterandMeshRenderer. Pick the shape inVisionFieldand assignAssets/Resources/VisionCone/VisionCone_mat.mat. - Add
VisionFieldDetectorand setTarget MaskandObstacle Mask; set the sameObstacle Maskon the mesh. - Enable Is Show Debug to see the gizmos when the object is selected.
- Subscribe to the detector events:
_detector.OnTargetDetected += enemy => Debug.Log($"Seen: {enemy.name}");
_detector.OnTargetLost += enemy => Debug.Log($"Lost: {enemy.name}");A target is a collider on the target layer with an Enemy component (Code.Enemy). Keep the owner's own colliders off the obstacle layers. Ready-made prefabs for all six shapes are in Assets/Resources/VisionCone/.
| Shape | Parameters |
|---|---|
Circle / Sector (CircleShape) |
Range, Angle (up to 360°) |
Arrow (ArrowShape) |
Width, Height, Tilt Angle (−45…45°) |
Half Ellipse (HalfEllipseShape) |
Width, Height, Pre Length, Length, Center Offset |
Offset Triangle (OffsetTriangleShape) |
Width, Height, Center Offset |
Square (RectangleShape) |
Width, Height |
Rhombus (RhombusShape) |
Side Length, Angle Degrees (10…170°) |
Every shape also has Segments (outline resolution).
- Mesh (
VisionFieldMesh):Occlusion Mode(Gpu,CpuRaycasts,None),Obstacle Mask,Raycast Offset(keeps the edge slightly in front of walls),Sort Order. - Detector (
VisionFieldDetector):Target Mask,Obstacle Mask,Detection Interval(default 0.1 s), optionalHeight Below/Height Above. - Material (
VisionField/Cone): base, edge and wave colours, edge width, occlusion softness, centre fade, wave spacing, speed and width.
| Area | Choice |
|---|---|
| Engine | Unity 6000.5.3f1, URP 17.5 (Forward) |
| Dependency injection | Zenject / Extenject (ProjectContext + SceneContext) |
| Async and tweens | UniTask, DOTween |
| Inspector and editor tools | Odin Inspector |
| UI | uGUI 2.5 + TextMesh Pro, View / Presenter split |
| Asset loading and saves | Resources via Zenject factories; PlayerPrefs + Odin serialization |
sequenceDiagram
participant Boot as Boot.unity
participant PC as ProjectContext<br/>(BootstrapInstaller)
participant Game as Game.unity<br/>(GameInstaller)
participant GS as GameStarter
participant HUD as LevelView / LevelPresenter
participant LC as LevelController
Boot->>PC: Zenject creates ProjectContext
PC->>PC: bind factories, providers, services
PC->>Game: SceneManager.LoadScene("Game")
Game->>GS: Initialize()
GS->>GS: player data, UI root, camera, player, enemies
GS->>HUD: create GameHud + LevelPresenter
HUD->>LC: PlayLevel(visionType, moveSpeed)
LC->>LC: VisionConeFactory creates the prefab under the player
LC->>LC: Player.SetTargetDetector → VisionAI
LC->>LC: PlayerMover.MoveAlongPath(path)
VisionConeFactory loads Resources/VisionCone/<VisionType>: the VisionType enum names must match the prefab names, and the enum order is the HUD dropdown order. VisionAI drives WeaponAI, a UniTask state sequence (idle → aim → shoot → idle) where each transition cancels the previous one.
Assets/
├── Code/ # runtime code (Game.asmdef), namespace "Code"
│ ├── VisionCone/ # the vision system
│ │ ├── VisionField.cs, VisionFieldMesh.cs, VisionFieldDetector.cs
│ │ ├── Shapes/ # VisionShape + 6 shapes, VisionShapeMath
│ │ ├── Occlusion/ # VisionOcclusion: GPU slice mask + polar atlas
│ │ ├── Factory/ # VisionConeFactory, VisionType
│ │ └── VisionAI.cs # detector → weapon bridge
│ ├── Infrastructure/ # Zenject installers, factories, services
│ ├── Levels/, Players/, Enemies/, Weapon/, Cameras/, UI/
│ └── Editors/ # editor tools (GameEditor.asmdef)
├── Resources/ # prefabs, VisionCone_mat and Shaders/, URP asset
├── ResourcesStatic/ # third-party art and VFX
├── Scenes/ # Boot.unity, Game.unity
└── Tests/ # EditMode + PlayMode
- Create
MyShape : VisionShape([Serializable]) with its parameters,ReachRadius,Contains(point),GetOutlinePoint(t)andGetParameterHash(). The formula and the outline must describe the same area. - In the Editor, create a prefab with
VisionField(your shape),VisionFieldMeshandVisionFieldDetectorinAssets/Resources/VisionCone/. - Add a value to the end of
VisionTypewhose name equals the prefab name; it appears in the HUD dropdown. - Add the shape to
VisionShapeTests,VisionPrefabTestsandVisionMeshGeometryTests, then run the tests.
| Tool | Where | What it does |
|---|---|---|
| Level path editor | LevelPathMover inspector |
Handles for every path point; add or delete points with hotkeys |
| Level Path Hotkeys Settings | Tools → Level Path Hotkeys Settings | The add/delete keys (default Q / E) |
| Prefab Batch Editor Window | Tools → Prefab Batch Editor Window | Apply a material and renderer settings to a prefab hierarchy |
| Rebuild | VisionFieldMesh inspector |
Rebuild the vision mesh in Edit Mode |
225 tests in Assets/Tests: EditMode (204) covers shapes, prefabs, mesh geometry, detection, GPU occlusion against physics raycasts, the rendered cone pixels and a 50-observer load test; PlayMode (21) runs the demo for every shape and measures the cost of 50 GPU-occluded cones.
Run them from Window → General → Test Runner, or from a terminal while the Editor is open:
unity command test run --mode editor --filter Tests.EditMode --filter-type Assembly
unity command test run --mode playmode --filter Tests.PlayMode --filter-type Assembly --async-tests trueThe project includes the AI Unity Pipeline: project rules for agents in CLAUDE.md (Claude Code) and AGENTS.md (Codex), the feature-cycle and chat-notes skills in .claude/skills, and the com.unity.pipeline package that lets the Unity CLI and MCP drive the open Editor. To connect your own agent, run unity mcp configure <client> --project-path <path-to-project>.
- Unity 6000.5.3f1 with URP 17.5.
- Odin Inspector, Zenject, UniTask and DOTween are included in
Assets/Plugins. The bundled Odin predates Unity 6.5 and logs editor exceptions on load; update it from the Asset Store.
MIT © 2025 SinlessDevil





