Scripting Support (C#)

advanced scripting

Volumetric Fog & Mist 2 (URP) · Scripting Support (C#)

The main scripting class is VolumetricFog (namespace VolumetricFogAndMist2). This MonoBehavior is attached to each fog volume GameObject. Fog appearance settings are stored in a VolumetricFogProfile ScriptableObject.

Use fog.profile to access the shared profile (changes affect all volumes sharing it). Use fog.settings to get an instanced copy that only affects this volume — similar to Unity’s sharedMaterial vs material.

VolumetricFog

Profile & Settings

VolumetricFogProfile profile

The shared fog profile asset. Changes affect all fog volumes that reference this profile.

VolumetricFogProfile settings property

Returns an instanced copy of the profile. Changes only affect this fog volume. Analogous to Unity’s material vs sharedMaterial.

Material material read-only

Returns the fog material used by this volume.

Lighting

bool enableNativeLights

Supports Unity native lights including point and spot lights. Default: false.

float nativeLightsMultiplier

Multiplier to native lights intensity. Default: 1.

float nativeLightFallOff

Native lights distance attenuation falloff. Range 0–1. Default: 1.

bool enablePointLights

Enable fast point lights (faster than native lights but cannot be combined with them). Default: false.

bool enableAPV

Supports Adaptive Probe Volumes (Unity 2023.1+). Default: false.

float apvIntensityMultiplier

Multiplier to APV intensity. Default: 1.

bool enableVoids

Enable fog voids (subtractive volumes that remove fog). Default: false.

Follow & Fade

bool enableFollow

Makes this fog volume follow another object automatically. Default: false.

Transform followTarget

The target transform to follow.

VolumetricFogFollowMode followMode

Follow mode: FullXYZ or RestrictToXZPlane. Default: RestrictToXZPlane.

bool followIncludeDistantFog

Also move distant fog when following the target. Default: false.

Vector3 followOffset

Offset from the follow target position.

bool enableFade

Fades fog in/out when the reference controller enters or exits the fog volume. Default: false.

bool fadeIncludeDistantFog

Also fades distant fog along with this volume. Default: false.

float fadeDistance

Fog blending starts within this fade distance from any volume border. Default: 1.

bool fadeOut

Fog disappears when the controller enters the volume (instead of appearing). Default: false.

Transform fadeController

The controller (player or camera) used to check for volume entry. Defaults to main camera if not set.

Sub-Volumes & Update

bool enableSubVolumes

Enable sub-volume blending. When the controller enters a sub-volume, the fog profile blends to the sub-volume’s profile. Default: false.

List<VolumetricFogSubVolume> subVolumes

List of allowed sub-volumes. If empty, any sub-volume in the scene can affect this fog volume.

bool enableUpdateModeOptions

Customize how this fog volume data is updated and animated. Default: false.

VolumetricFogUpdateMode updateMode

When to update fog data: WhenFogVolumeIsVisible or WhenCameraIsInsideArea. Default: WhenFogVolumeIsVisible.

Camera updateModeCamera

Camera used to compute visibility. Uses main camera if not set.

Bounds updateModeBounds

Bounds for WhenCameraIsInsideArea mode. Default: center (0,0,0), size (100,100,100).

bool showBoundary

Shows the fog volume boundary in the Game View. Default: false.

Fog of War Properties

bool enableFogOfWar

Enable fog of war feature. Default: false.

Vector3 fogOfWarCenter

World-space center of the fog of war coverage area.

bool fogOfWarIsLocal

Whether the fog of war center is relative to the transform position. Default: false.

Vector3 anchoredFogOfWarCenter read-only

Returns the world-space fog of war center, offset by the transform position if fogOfWarIsLocal is true.

Vector3 fogOfWarSize

World-space size of the fog of war coverage area. Default: (1024, 0, 1024).

bool fogOfWarShowCoverage

Show fog of war coverage gizmo in the Scene View. Default: false.

int fogOfWarTextureWidth

Width of the fog of war texture. Range 32–2048. Default: 256.

int fogOfWarTextureHeight

Height of the fog of war texture. Range 32–2048. Use 0 to match width.

float fogOfWarRestoreDelay

Delay in seconds before cleared fog starts restoring. Set to 0 to keep cleared areas permanent. Range 0–100.

float fogOfWarRestoreDuration

Duration in seconds of the fog restore transition. Range 0–25. Default: 2.

float fogOfWarSmoothness

Border smoothness of cleared fog areas. Range 0–1. Default: 1.

bool fogOfWarBlur

Apply blur to the fog of war texture for smoother edges. Default: false.

Texture2D fogOfWarTexture property

Gets or sets the fog of war texture. Setting this reloads the texture data.

Color32[] fogOfWarTextureData property

Gets or sets the raw fog of war color buffer. The alpha channel controls fog opacity: 0 = fully cleared, 255 = full fog. Useful for saving/loading fog of war state.

Fog of War Methods

void SetFogOfWarAlpha(Vector3 worldPosition, float radius, float fogNewAlpha, float duration = 0)

Changes fog of war opacity at a world position within a circular radius. Set fogNewAlpha to 0 to clear fog, 1 to restore.

void SetFogOfWarAlpha(Vector3 worldPosition, float radius, float fogNewAlpha, float duration, float smoothness)

Same as above with an additional smoothness parameter for the cleared area border.

void SetFogOfWarAlpha(Vector3 worldPosition, float radius, float fogNewAlpha, float duration, float smoothness, FoWUpdateMethod updateMethod, bool blendAlpha = true)

Circular fog of war with explicit update method (main thread or background thread) and blend mode.

void SetFogOfWarAlpha(Vector3 worldPosition, float radius, float fogNewAlpha, bool blendAlpha, float duration, float smoothness, float restoreDelay, float restoreDuration, float restoreToAlphaValue = 1f, FoWUpdateMethod updateMethod = FoWUpdateMethod.BackgroundThread)

Full circular fog of war with all options including auto-restore after a delay.

void SetFogOfWarAlpha(Bounds bounds, float fogNewAlpha, float duration = 0)

Changes fog of war opacity within a rectangular bounds area.

void SetFogOfWarAlpha(Bounds bounds, float fogNewAlpha, float duration, float smoothness)

Bounds-based fog of war with smoothness control.

void SetFogOfWarAlpha(Bounds bounds, float fogNewAlpha, bool blendAlpha, float duration)

Bounds-based fog of war with blend mode control.

void SetFogOfWarAlpha(Bounds bounds, float fogNewAlpha, bool blendAlpha, float duration, float smoothness, float restoreDelay, float restoreDuration, float restoreToAlpha = 1f, FoWUpdateMethod updateMethod = FoWUpdateMethod.BackgroundThread)

Full bounds-based fog of war with all options including auto-restore.

void SetFogOfWarAlpha(Collider collider, float fogNewAlpha)

Changes fog of war opacity within a convex collider shape.

void SetFogOfWarAlpha(Collider collider, float fogNewAlpha, bool blendAlpha = false, float duration = 0, float smoothness = 0, float restoreDelay = 0, float restoreDuration = 2, float restoreToAlpha = 1f)

Collider-based fog of war with all options.

void SetFogOfWarAlpha(GameObject go, float fogNewAlpha)

Changes fog of war opacity within a mesh shape defined by a GameObject.

void SetFogOfWarAlpha(GameObject go, float fogNewAlpha, float duration = 0, float restoreDelay = 0, float restoreDuration = 2, float restoreToAlpha = 1f, FoWUpdateMethod updateMethod = FoWUpdateMethod.BackgroundThread)

Mesh-based fog of war with restore and threading options.

void SetFogOfWarAlpha(GameObject go, Vector3[] positions, float fogNewAlpha, float duration = 0, float restoreDelay = 0, float restoreDuration = 2, float restoreToAlpha = 1f, FoWUpdateMethod updateMethod = FoWUpdateMethod.BackgroundThread) new

Batched: stamps a mesh shape at multiple positions in a single call, applying the same alpha to all. Ideal for tile-based fog of war (hex grids, strategy maps).

void SetFogOfWarAlpha(GameObject go, Vector3[] positions, float[] fogNewAlphas, float duration = 0, float restoreDelay = 0, float restoreDuration = 2, float restoreToAlpha = 1f, FoWUpdateMethod updateMethod = FoWUpdateMethod.BackgroundThread) new

Batched: stamps a mesh shape at multiple positions with per-position alpha values.

void ResetFogOfWar(float alpha = 1f)

Resets the entire fog of war texture to the given opacity.

void ResetFogOfWarAlpha(Vector3 worldPosition, float radius, float alpha = 1f)

Restores fog of war at a circular area.

void ResetFogOfWarAlpha(Bounds bounds, float alpha = 1f)

Restores fog of war within a rectangular bounds.

void ResetFogOfWarAlpha(Collider collider, float alpha = 1f)

Restores fog of war within a collider shape.

void ResetFogOfWarAlpha(GameObject go, float alpha = 1f)

Restores fog of war within a mesh shape.

void ResetFogOfWarAlpha(Vector3 position, Vector3 size, float alpha = 1f)

Restores fog of war at a position with a given size.

void ResetFogOfWarAlpha(Vector3 position, float extentsX, float extentsZ, float alpha = 1f)

Restores fog of war at a position with given X/Z extents.

float GetFogOfWarAlpha(Vector3 worldPosition)

Returns the current fog of war alpha at a world position (0 = cleared, 1 = full fog).

void ReloadFogOfWarTexture()

Reloads the current contents of the fog of war texture and uploads it to the GPU.

void UpdateFogOfWar(bool forceUpload = false)

Updates fog of war transitions (restore timers) and uploads texture changes to the GPU.

Methods

void UpdateMaterialProperties()

Schedules a material properties update at end of frame. Call after modifying profile fields at runtime.

void UpdateMaterialProperties(bool forceTerrainCaptureUpdate)

Schedules a material properties update, optionally forcing a terrain capture refresh.

void UpdateMaterialPropertiesNow(bool skipTerrainCapture = false, bool forceTerrainCaptureUpdate = false)

Forces an immediate material properties update instead of deferring to end of frame.

void PerformHeightmapCapture()

Updates the terrain heightmap capture for this fog volume. Call after terrain modifications when using terrain fit.

Bounds GetBounds()

Returns the world-space bounds of the fog volume.

void SetBounds(Bounds bounds)

Sets the position and scale of the fog volume from the given bounds.

void RegisterFogMat(Material fogMat)

Registers an additional material to receive fog shader properties. Useful for custom shaders that need to sample the fog.

void UnregisterFogMat(Material fogMat)

Unregisters a material from receiving fog shader properties.

Static Members

static List<VolumetricFog> volumetricFogs read-only

Static list of all active VolumetricFog instances in the scene.

static void FindAlphaClippingObjects()

Refreshes the list of renderers used for the depth pre-pass alpha clipping. Call after creating new transparent objects at runtime.

static void AddAlphaClippingObject(Renderer renderer)

Adds a specific renderer to the alpha clipping depth pre-pass.

static void RemoveAlphaClippingObject(Renderer renderer)

Removes a specific renderer from the alpha clipping depth pre-pass.

Events

event OnUpdateMaterialPropertiesEvent OnUpdateMaterialProperties(VolumetricFog fogVolume)

Fired when the fog volume’s material properties are updated.

Delegate: void OnUpdateMaterialPropertiesEvent(VolumetricFog fogVolume)

VolumetricFogProfile

Rendering

int raymarchQuality

Number of raymarching samples. Higher values are more accurate but slower. Range 1–16. Default: 6.

float raymarchNearStepping

Increases samples at short distances for better near-camera detail. Range 0–50. Default: 8.

float raymarchMinStep

Minimum step size for raymarching. Default: 0.1.

float jittering

Jittering amount to reduce banding artifacts. Default: 0.5.

float dithering

Dithering amount. Range 0–2. Default: 1.

int renderQueue

Render queue for the fog material. Default: 3100.

int sortingLayerID

Optional sorting layer ID. Default: 0.

int sortingOrder

Optional sorting order within the sorting layer. Default: 0.

Density & Noise

float density

Overall fog density. Default: 1.

bool constantDensity

Do not use any noise — produces uniform fog. Default: false.

Texture2D noiseTexture

Main noise texture used for fog density variation.

float noiseStrength

Noise strength. Range 0–3. Default: 1.

float noiseScale

Noise scale (world-space size of the noise pattern). Default: 15.

float noiseFinalMultiplier

Final multiplier applied to the noise result. Default: 1.

bool useDetailNoise

Enable detail noise for finer density variation. Default: false.

Texture3D detailTexture

3D texture used for detail noise.

float detailScale

Detail noise scale. Default: 0.35.

float detailStrength

Detail noise strength. Range 0–1. Default: 0.5.

float detailOffset

Detail noise offset. Default: -0.5.

Geometry

VolumetricFogShape shape

Volume shape: Box, Sphere, or Custom. Default: Box.

float border

Border fade (soft edges). Range 0–1. Default: 0.05.

float scaleNoiseWithHeight

Scales noise with volume height. Range 0–1. Default: 0.

bool customHeight

Ignores volume height and uses a custom height from the profile. Default: false.

float height

Custom height value (used when customHeight is true). Default: 0.

float verticalOffset

Vertical offset for the fog density within the volume. Default: 0.

float distance

Minimum distance from camera for fog to appear. Default: 0.

float distanceFallOff

Distance fall-off. Range 0–1. Default: 0.93.

float maxDistance

Maximum distance from camera. Default: 10000.

float maxDistanceFallOff

Fall-off at max distance. Range 0–1. Default: 0.

Mesh customMesh

Custom mesh used when shape is set to Custom.

Terrain Fit

bool terrainFit

Fits fog altitude to the terrain heightmap. Default: false.

HeightmapCaptureResolution terrainFitResolution

Resolution of the heightmap capture: _64, _128, _256, _512, or _1024. Default: _128.

LayerMask terrainLayerMask

Which objects are included in the heightmap capture. Default: Everything.

float terrainFogHeight

Height of fog above the terrain surface. Default: 25.

float terrainFogMinAltitude

Minimum altitude for terrain-fitted fog. Default: 0.

float terrainFogMaxAltitude

Maximum altitude for terrain-fitted fog. Default: 150.

Colors

Color albedo

Fog base color. Default: light gray.

float brightness

Overall brightness multiplier. Default: 1.

float deepObscurance

Darkens fog in thicker/deeper areas. Range 0–2. Default: 1.

Color specularColor

Specular highlight color. Default: (1, 1, 0.8).

float specularThreshold

Specular threshold. Range 0–1. Default: 0.637.

float specularIntensity

Specular intensity. Range 0–1. Default: 0.428.

bool enableDepthGradient

Enable depth-based color gradient. Default: false.

Gradient depthGradient

Depth gradient (HDR, linear interpolation).

float depthGradientMaxDistance

Maximum distance for the depth gradient. Default: 1000.

bool enableHeightGradient

Enable height-based color gradient. Default: false.

Gradient heightGradient

Height gradient (HDR, linear interpolation).

Animation

float turbulence

Turbulence speed. Default: 0.73.

Vector3 windDirection

Wind direction and speed. Default: (0.02, 0, 0).

bool useCustomDetailNoiseWindDirection

Use a separate wind direction for detail noise. Default: false.

Vector3 detailNoiseWindDirection

Wind direction for detail noise. Default: (0.02, 0, 0).

Directional Light

bool dayNightCycle

Syncs fog lighting with the Sun/Moon from the Volumetric Fog Manager. Default: true.

Vector3 sunDirection

Custom sun direction (used when dayNightCycle is disabled). Default: Vector3.up.

Color sunColor

Custom sun color (used when dayNightCycle is disabled).

float sunIntensity

Custom sun intensity. Default: 1.

float ambientLightMultiplier

Influence of ambient light on fog. Default: 0.

DiffusionModel lightDiffusionModel

Light diffusion model: Simple, Smooth, or Strong. Default: Simple.

float lightDiffusionPower

Light diffusion power. Range 1–256. Default: 32.

float lightDiffusionIntensity

Light diffusion intensity. Default: 0.4.

float lightDiffusionNearDepthAtten

Near depth attenuation for light diffusion. Default: 0.

bool receiveShadows

Enable shadow reception from the directional light. Default: false.

float shadowIntensity

Shadow intensity. Range 0–1. Default: 0.5.

float shadowCancellation

Removes fog in shadowed areas. Range 0–1. Default: 0.

float shadowMaxDistance

Maximum distance for shadow rendering. Default: 250.

bool cookie

Uses the directional light’s cookie texture on the fog. Default: false.

Distant Fog

bool distantFog

Enables exponential distant fog for horizon/sky coverage. Default: false.

bool distantFogShowInEditMode

Show distant fog in edit mode. Default: true.

float distantFogStartDistance

Start distance for distant fog. Default: 1000.

float distantFogDistanceDensity

Distance density. Default: 0.5.

float distantFogMaxHeight

Maximum height. Default: 4000.

float distantFogHeightDensity

Height density. Default: 0.5.

Color distantFogColor

Distant fog color. Default: dark gray.

float distantFogDiffusionIntensity

Light diffusion intensity for distant fog. Default: 0.4.

int distantFogRenderQueue

Render queue. Default: 2999.

float distantFogBaseAltitude

Base altitude. Default: 0.

bool distantFogSymmetrical

Symmetrical distant fog. Default: false.

bool distantFogTransparencySupport

Enables transparency support via depth peeling. Default: false.

bool distantFogNoise

Enables noise for distant fog. Default: false.

Texture3D distantFogNoiseTexture

Noise texture for distant fog.

float distantFogDistanceNoiseScale

Noise scale. Default: 0.1.

float distantFogDistanceNoiseStrength

Noise strength. Range 0–1. Default: 0.5.

float distantFogDistanceNoiseMaxDistance

Max distance for noise fade out. Default: 250.

Vector3 distantFogNoiseWindDirection

Wind direction for distant fog noise. Default: (0.002, 0.002, 0).

Methods & Events

void ValidateSettings()

Validates and clamps all profile settings to their valid ranges.

void Lerp(VolumetricFogProfile p1, VolumetricFogProfile p2, float t)

Interpolates all profile settings between two profiles by factor t (0–1). Useful for smooth transitions between fog configurations.

event OnSettingsChanged onSettingsChanged()

Fired when profile settings are modified.

Delegate: void OnSettingsChanged()

Code Examples

Runtime Fog Modification

using UnityEngine;
using VolumetricFogAndMist2;

public class FogController : MonoBehaviour {
    VolumetricFog fog;

    void Start() {
        fog = GetComponent<VolumetricFog>();

        // Modify instanced profile (only this volume)
        fog.settings.density = 2f;
        fog.settings.albedo = new Color(0.5f, 0.6f, 0.7f);
        fog.settings.windDirection = new Vector3(0.05f, 0, 0);
        fog.UpdateMaterialProperties();
    }

    void Update() {
        // Animate density over time
        fog.settings.density = 1f + Mathf.Sin(Time.time) * 0.5f;
        fog.UpdateMaterialProperties();
    }
}

Follow Target Setup

VolumetricFog fog = GetComponent<VolumetricFog>();
fog.enableFollow = true;
fog.followTarget = player.transform;
fog.followMode = VolumetricFogFollowMode.RestrictToXZPlane;
fog.followOffset = new Vector3(0, -2, 0);

Fog of War

VolumetricFog fog = GetComponent<VolumetricFog>();

// Clear fog at player position (circular)
fog.SetFogOfWarAlpha(player.position, radius: 15f, fogNewAlpha: 0f);

// Clear fog within bounds (rectangular)
fog.SetFogOfWarAlpha(new Bounds(center, size), fogNewAlpha: 0f);

// Clear fog matching a collider shape
fog.SetFogOfWarAlpha(areaCollider, fogNewAlpha: 0f);

// Clear with auto-restore after 5 seconds
fog.SetFogOfWarAlpha(player.position, 10f, fogNewAlpha: 0f,
    blendAlpha: true, duration: 0.5f, smoothness: 1f,
    restoreDelay: 5f, restoreDuration: 3f);

// Query fog opacity at a position
float alpha = fog.GetFogOfWarAlpha(targetPosition);

// Reset all fog of war
fog.ResetFogOfWar();

Batched Fog of War (Hex Grids / Tile Maps)

VolumetricFog fog = GetComponent<VolumetricFog>();

// A mesh representing a single tile shape (e.g. hexagon)
public GameObject tileMeshPrefab;

// Reveal multiple tiles at once with the same alpha
Vector3[] tileCenters = new Vector3[] {
    new Vector3(10, 0, 20),
    new Vector3(12, 0, 22),
    new Vector3(14, 0, 20)
};
fog.SetFogOfWarAlpha(tileMeshPrefab, tileCenters, fogNewAlpha: 0f);

// Per-tile alpha values (e.g. partial visibility)
float[] alphas = new float[] { 0f, 0.3f, 0f };
fog.SetFogOfWarAlpha(tileMeshPrefab, tileCenters, alphas, duration: 0.5f);

Profile Interpolation

public VolumetricFogProfile daytimeProfile;
public VolumetricFogProfile nightProfile;

void UpdateFogForTimeOfDay(float t) {
    VolumetricFog fog = GetComponent<VolumetricFog>();
    fog.settings.Lerp(daytimeProfile, nightProfile, t);
    fog.UpdateMaterialProperties();
}

Saving & Loading Fog of War State

VolumetricFog fog = GetComponent<VolumetricFog>();

// Save state
Color32[] savedState = fog.fogOfWarTextureData;

// Load state
fog.fogOfWarTextureData = savedState;
Was this page helpful?