A URP Unity script that dynamically adjusts camera Depth of Field in real time to keep the focal point perfectly in focus. Designed to work seamlessly with the companion script CameraController.
AutoFocus.cs reads the focal point assigned in CameraController.cs and dynamically adjusts the Depth of Field (DoF) parameter in a URP Global Volume.
This keeps the selected object or scene point perfectly in focus โ ideal for cinematic orbit cameras, XR/VR rigs, and animated camera moves.
- Works with URP Volume Depth of Field component
- Automatically detects and syncs with your CameraController
- Adjusts focus distance every frame
- Zero dependencies โ plug and play
- Compatible with Unity 2022+ URP
- Unity URP project
- A Global Volume with a Depth of Field override enabled
CameraController.cs(download from here)
- The script accesses the
DepthOfFieldcomponent from your Volume Profile. - It gets the current focalPoint from the attached
CameraController. - Calculates the distance between the camera and that focal point.
- Updates
dof.focusDistancein real-time.
float distance = Vector3.Distance(transform.position, focalPoint.transform.position);
dof.focusDistance.value = distance;-
Assign URP Asset
- In Project Settings โ Graphics, assign your URP pipeline asset.
- Enable Post Processing and Depth Texture.
-
Add a Volume
- Create a Global Volume โ Add Override โ Post-processing โ Depth of Field.
- Set Mode to Bokeh and tweak focus parameters.
-
Attach Scripts
- Add
CameraController.csto your camera (handles orbit, pan, zoom). - Add
AutoFocus.csto the same GameObject. - Drag your Volume into the
Volumefield ofAutoFocus.
- Add
-
Play
- Move or animate the
focalPointโ the camera focus updates automatically.
- Move or animate the
| Variable | Type | Description |
|---|---|---|
volume |
Volume |
Reference to the Global Volume containing Depth of Field |
cameraController |
CameraController |
Camera control script providing the focal point |
A demo scene could include:
- A camera orbiting around a target sphere
- A Global Volume with DoF enabled
- AutoFocus attached to the same camera
MIT License โ feel free to use, modify, and share.
- ๐ฎ CameraController: Scene-view-style orbit, pan, and zoom controller for Unityโs new Input System.