VisionFieldMesh is a modular field-of-view (FOV) system for Unity. It combines a procedural vision mesh that is clipped by 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 |
![]() |
1.3.mp4
1.2.mp4
1.1.mp4
- One shape, drawn and detected the same way: six shapes, each described once and shared by the mesh and the detector.
- Cheap detection: shape formula plus a few line-of-sight rays, 10 times a second.
- GPU occlusion: the field is hidden behind walls per pixel by a shader; 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.
RaycastOffsetkeeps the field's edge slightly in front of walls.- Target detection with shape tests, height limits, and line-of-sight raycasts.
- Events:
OnTargetDetectedandOnTargetLostfire only when the visible target changes. - Debug gizmos: the shape outline in yellow, free rays in green, clipped rays in red, and the current target in cyan.
- Editor-time preview: the
[ExecuteAlways]mesh updates as you edit the shape; a Rebuild button forces it. - 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 (VisionShape: circle/sector, rectangle, rhombus, arrow, offset triangle, half ellipse). The shape knows its outline, its reach and aContains(point)formula, and 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. InGpumode (default) walls are handled per pixel;CpuRaycastsis a fallback that clips the vertices with raycasts.VisionOcclusiondoes the GPU work once per frame for up to 64 cones: it draws where obstacle colliders cross the plane at eye height into a top-down mask, then measures, for every cone and 512 directions, the distance to the first wall. The cone shader reads that distance and fades out everything behind it. 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
VisionFieldDetectordetects analytically, 10 times a second by default: one overlap query finds candidates, the shape's formula checks whether each is inside, and only those get up to three line-of-sight rays. It returns the nearest visible enemy. 50 observers watching 50 enemies cost about 0.3 ms per detection pass in the Editor.
- 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 from the dropdown, enter a movement speed, and press Start.
- The player follows the level path. When an enemy enters the field, the turret aims and fires, and the enemy disappears with a VFX.
- Create a GameObject (it looks along its forward axis) and add
VisionFieldMesh— it addsVisionField,MeshFilterandMeshRenderer. Pick the shape inVisionFieldand assign theVisionCone_matmaterial (Assets/Resources/VisionCone/VisionCone_mat.mat, shaderVisionField/Cone). - Add
VisionFieldDetectorand setTarget MaskandObstacle Mask; set the sameObstacle Maskon the mesh. - The field updates in the Scene view as you edit the shape; Rebuild forces it.
- Enable Is Show Debug to see the outline, clip rays and current target as 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}");Targets are found by component: a collider on the target layer must have an Enemy component (Code.Enemy). Keep the owner's own colliders off the obstacle layers — the demo player uses a separate Player layer so its field never clips against itself.
Ready-made prefabs for all six shapes are in Assets/Resources/VisionCone/.
Mesh settings (VisionFieldMesh): Cone Material, Sort Order, Occlusion Mode (Gpu, CpuRaycasts, None), Obstacle Mask, Raycast Offset.
Material settings (VisionField/Cone): base, edge and wave colours, edge width, occlusion softness, centre fade, wave spacing, speed and width.
Detector settings (VisionFieldDetector): Target Mask, Obstacle Mask, Detection Interval (seconds between checks, default 0.1), optional height window (Height Below / Height Above).
Every shape also has Segments (outline resolution).
| 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°) |
| Area | Choice |
|---|---|
| Engine | Unity 6000.5.3f1, URP 17.5.0 (Forward; depth/opaque textures and HDR off) |
| Dependency injection | Zenject / Extenject (ProjectContext + SceneContext) |
| Async | UniTask |
| Tweens | DOTween |
| Inspector & editor tools | Odin Inspector (attributes, OdinEditorWindow, serialization) |
| UI | uGUI 2.5 + TextMesh Pro, View / Presenter split |
| Tests | Unity Test Framework 1.7 (EditMode + PlayMode) |
| Asset loading | Resources through IInstantiator.InstantiatePrefabResource |
| Saves | PlayerPrefs + Odin JSON 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->>PC: StaticDataService.LoadData()
PC->>Game: SceneManager.LoadScene("Game")
Game->>GS: Initialize()
GS->>GS: load or create PlayerData
GS->>GS: 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)
BootstrapInstaller(onAssets/Resources/ProjectContext.prefab) is the app-wide composition root. It bindsPlayerFactory,EnemyFactory,VisionConeFactory,UIFactory, the camera, player and enemy providers,PrefsSaveLoadService,PersistenceProgressService,LevelControllerandStaticDataService.GameInstaller(onSceneContext_GameinGame.unity) holds the scene references (player spawn point, enemy spawn points,LevelPathMover), bindsGameStarterandGameUpdater, and forwardsUpdate()toGameUpdater, which drivesCameraFollowing.VisionConeFactoryloadsResources/VisionCone/<VisionType>. TheVisionTypeenum names must match the prefab names, and the enum order is the HUD dropdown order.VisionAIlistens to the detector and drivesWeaponAI, a small UniTask state sequence: idle (bobbing via DOTween) → aim and follow the target → shoot (VFX,Enemy.SetDead()) → idle. Each transition cancels the previous one, and everything stops when the weapon is destroyed.
Assets/
├── Code/ # Game.asmdef (runtime), root namespace "Code"
│ ├── Cameras/ # CameraFollowing, ICameraProvider
│ ├── Editors/ # GameEditor.asmdef: path editor, hotkeys, prefab batch tool
│ ├── Enemies/ # Enemy, EnemyFactory, EnemyProvider
│ ├── Infrastructure/
│ │ ├── BootstrapInstaller.cs # app-wide Zenject installer
│ │ ├── GameInstaller.cs # Game scene installer
│ │ ├── Factory/ # base Factory, UIFactory
│ │ ├── Services/ # GameStarter, GameUpdater, SaveLoad, PersistenceProgress, StaticData
│ │ └── StaticData/ # ScriptableObject data types
│ ├── Levels/ # LevelController, LevelPathMover
│ ├── Players/ # Player, PlayerMover, PlayerFactory, PlayerProvider
│ ├── UI/ # GameHud, LevelView, LevelPresenter
│ ├── Utilities/Extensions/ # extension methods
│ ├── VisionCone/ # the vision system
│ │ ├── VisionField.cs # holds the shape
│ │ ├── VisionFieldMesh.cs # draws it
│ │ ├── VisionFieldDetector.cs # detects inside it
│ │ ├── Shapes/ # VisionShape + 6 shapes, VisionShapeMath
│ │ ├── Occlusion/ # VisionOcclusion: GPU slice mask + polar atlas
│ │ ├── Factory/ # VisionConeFactory, VisionType
│ │ ├── Provider/ # placeholder
│ │ └── VisionAI.cs # detector → weapon bridge
│ └── Weapon/ # Weapon (DOTween), WeaponAI (UniTask states)
├── Plugins/ # Zenject, UniTask, DOTween, Odin Inspector, TextMesh Pro
├── Resources/ # runtime-loaded prefabs and configs
│ ├── ProjectContext.prefab, SceneContext_*.prefab
│ ├── VisionCone/ # 6 vision prefabs, VisionCone_mat, Shaders/
│ ├── Player/, Enemies/, UI/ # spawned prefabs
│ ├── StaticData/ # ScriptableObject assets
│ └── URP/ # URP asset and renderer
├── ResourcesStatic/ # art & VFX: Stickman, Hypercasual Action Props, Cartoon FX, Toony Colors Pro
├── Scenes/ # Boot.unity, Game.unity
└── Tests/ # EditMode + PlayMode test assemblies
- 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(pick your shape),VisionFieldMeshandVisionFieldDetectorinAssets/Resources/VisionCone/. - Add the shape to
VisionShapeTests, which checks the formula against the outline. - Add a value to the end of
VisionTypewhose name equals the prefab name. It appears in the HUD dropdown automatically. - Register the shape in
VisionPrefabTestsandVisionMeshGeometryTests, then run the tests.
| Tool | Where | What it does |
|---|---|---|
| Level path editor | LevelPathMover inspector |
Position handles for every path point; add or delete points with hotkeys |
| Level Path Hotkeys Settings | Tools → Level Path Hotkeys Settings | Configure the add/delete point keys (default Q / E) |
| Prefab Batch Editor Window | Tools → Prefab Batch Editor Window | Apply a material and renderer settings to a whole prefab hierarchy |
| Rebuild | VisionFieldMesh inspector (Odin button) |
Rebuild the vision mesh in Edit Mode |
225 automated tests live in Assets/Tests:
| Suite | Count | What it checks |
|---|---|---|
EditMode (Tests.EditMode) |
204 | Prefab wiring, shape types and layer masks, shape formula vs. outline agreement, GPU occlusion vs. physics (sandbox and the real level), final cone pixels rendered from above, mesh geometry (valid upward triangles, full shape, wall clipping, sector area), detector vs. drawn field (inside seen, outside ignored, walls block, nearest wins, events), shape math, a 50-observer load test, Resources and scene integrity, Zenject bindings, HUD input parsing, save/load |
PlayMode (Tests.PlayMode) |
21 | Boot → Game, PlayLevel for every shape, level restart, the full demo path for every shape, PlayerMover, reloading Game while the weapon aims, 50-cone GPU occlusion cost |
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 true
unity command test status --detail failuresThe project includes the AI Unity Pipeline setup for coding agents:
| Part | Purpose |
|---|---|
CLAUDE.md |
Project rules for Claude Code: architecture, conventions, Git style, CLI commands, tests |
AGENTS.md |
The same rules for OpenAI Codex |
.claude/skills/feature-cycle |
Implement a feature in a feature/<name> branch, verify it in Unity, and leave Docs/Features/<name>/Status.md |
.claude/skills/chat-notes |
Save a dated summary of a chat to Docs/ |
com.unity.pipeline |
Unity Pipeline package: lets the Unity CLI and MCP drive the open Editor |
| Unity MCP | unity mcp --project-path <project> registered as an MCP server for the agent |
| Unity agent plugin | Official unity@unity-agent-plugin skills for Claude Code |
To connect your own agent, install the Unity CLI, open the project, then run unity mcp configure <client> --project-path <path-to-project> (see unity mcp configure --list).
- One cross-section for all cones, at their average eye height: cones on very different floors share it.
- Walls block from both sides; trigger colliders are ignored; box, sphere, capsule and mesh colliders are supported.
- The mask covers all cones (up to 256 m across, 1024 texels), so very spread-out cones get a coarser mask.
- Up to 64 GPU-occluded cones; more are drawn without occlusion (a warning is logged).
- The slice and polar passes need shader model 4.5 (raw buffers): DX11/12, Vulkan, Metal, GLES 3.1+.
- Pressing Start again restarts the level: the previous vision field is removed, enemies are revived, and the player starts the path from the beginning with the newly selected shape.
- The HUD number is the movement speed (units per second, minimum
0.1). Both1.5and1,5are accepted. - Every detector reports the nearest visible target.
- Unity 6000.5.3f1 (the pinned version) with URP 17.5
- Odin Inspector (vision components use its attributes and buttons). The bundled version predates Unity 6.5 and logs editor exceptions on load; update it from the Asset Store.
- Zenject/Extenject, UniTask and DOTween for the demo game (included in
Assets/Plugins)
MIT © 2025 SinlessDevil





