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.
1.3.mp4
1.2.mp4
1.1.mp4
- π§© Procedural vision mesh for six shapes, rebuilt only when its parameters or transform change.
- π§± Obstacle clipping: every edge ray is raycast against an obstacle mask, so the field stops at walls.
- π
RaycastOffsetpulls the clipped edge back from surfaces to avoid z-fighting and clipping. - π― Target detection with shape tests, height limits, and line-of-sight raycasts.
- π£ Events:
OnTargetDetectedandOnTargetLostfire only when the visible target changes. - π§ͺ Debug gizmos: free rays in green, blocked rays in red, rays that hit targets in yellow, and detected targets in cyan.
- π οΈ Editor-time preview:
[ExecuteAlways]meshes with Create Mesh / Delete Mesh buttons. - β»οΈ Extensible: a new shape is one mesh class, one detector class, and a prefab.
Each vision prefab carries two components that work independently:
flowchart LR
subgraph Prefab["Vision prefab (Resources/VisionCone)"]
Mesh["BaseVisionMesh subclass<br/>draws the field"]
Detector["BaseTargetDetector subclass<br/>finds targets"]
end
Obstacles[("Obstacle layer")]
Targets[("Target layer")]
Mesh -- "edge raycasts" --> Obstacles
Detector -- "OverlapSphere / shape test" --> Targets
Detector -- "line-of-sight raycast" --> Obstacles
Detector -- "OnTargetDetected / OnTargetLost" --> VisionAI
VisionAI --> WeaponAI["WeaponAI<br/>aim β shoot β idle"]
BaseVisionMeshowns theMeshFilterandMeshRenderer. Each subclass builds its outline from_precision/_segmentsdirections, raycasts each one against_obstacleMask, and writes the vertices, triangles, normals and UVs into a dynamic mesh. Shadows, light probes and occlusion are turned off on the renderer.BaseTargetDetectorcallsFindVisibleTarget()in everyUpdate(), compares the result with the previous frame and raisesOnTargetLostandOnTargetDetected.RaycastTargetDetector(Arrow, Half Ellipse, Offset Triangle, Square, Rhombus) casts a ray from the shape centre to every outline point β the same fan the mesh is built from β and returns the nearest enemy that no obstacle hides.TargetCircleDetectorusesOverlapSpherewith angle, height and line-of-sight checks.
The mesh and the detector have separate shape parameters (width, height, angle, and so on). Keep them identical when you tune a prefab β a test checks this.
- 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 and add a vision mesh component (for example
VisionCircleMesh). Assign aMeshFilter, aMeshRendererand a material (Assets/Resources/VisionCone/Vision_mat.mat). - Add the matching detector (for example
TargetCircleDetector) and assignBody(the transform that looks forward),Target MaskandObstacle Mask. - Set
Obstacle Maskon the mesh as well, then press Create Mesh to preview it in the Scene view. - Enable Is Show Debug to see rays and hits 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/.
Shared mesh settings (BaseVisionMesh): Obstacle Mask, Cone Material, Sort Order, Precision.
Shared detector settings (BaseTargetDetector): Target Mask, Obstacle Mask, Body, Is Show Debug, Precision.
| Shape | Main parameters |
|---|---|
| Circle / Sector | Vision Angle (up to 360Β°), Vision Range, Raycast Offset; detector also has Height Above / Height Below |
| Arrow | Width, Height, Tilt Angle (β45β¦45Β°), Segments, Raycast Offset |
| Half Ellipse | Width, Height, Center Offset, Pre Length, Length, Segments, Raycast Offset |
| Offset Triangle | Width, Height, Center Offset, Segments, Raycast Offset |
| Square | Width, Height, Segments, Raycast Offset |
| Rhombus | Side Length, Angle Degrees (10β¦170Β°), Segments, Raycast Offset |
| 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.SetBaseTargetDetector β 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
β β βββ Visions/ # BaseVisionMesh + 6 shapes
β β βββ Detectors/ # BaseTargetDetector, RaycastTargetDetector + 6 shapes
β β βββ 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 + Vision_mat
β βββ 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
VisionMyShapeMesh : BaseVisionMeshand implementGenerateMesh(). OverrideParamsChanged()/CacheParams()for your parameters. - Create
TargetMyShapeDetector : RaycastTargetDetectorand implementRayOrigin,EdgePointCountandGetEdgePointWorld(i)with the same outline formula as the mesh. - In the Editor, create a prefab with both components in
Assets/Resources/VisionCone/. - 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 |
| Create / Delete Mesh | BaseVisionMesh inspector (Odin buttons) |
Build or remove the vision mesh in Edit Mode |
135 automated tests live in Assets/Tests:
| Suite | Count | What it checks |
|---|---|---|
EditMode (Tests.EditMode) |
115 | Prefab wiring and layer masks, mesh/detector parameter parity, mesh geometry (valid upward triangles, full shape, wall clipping, sector area), detector vs. drawn field (inside seen, outside ignored, walls block, nearest wins, events), Resources and scene integrity, Zenject bindings, HUD input parsing, save/load |
PlayMode (Tests.PlayMode) |
20 | Boot β Game, PlayLevel for every shape, level restart, the full demo path for every shape, PlayerMover, reloading Game while the weapon aims |
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).
- 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





