Scripting Support (C#)

advanced scripting

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

Control Dynamic Fog & Mist 2 at runtime using the DynamicFogAndMist2 namespace. The fog system uses two main classes: DynamicFog (the MonoBehavior component placed on a volume object) and DynamicFogProfile (a ScriptableObject that holds all visual settings).

using DynamicFogAndMist2;

DynamicFog fog = GetComponent<DynamicFog>();
fog.profile.density = 0.5f;
fog.UpdateMaterialProperties();

DynamicFog

MonoBehavior component attached to a fog volume GameObject. Manages rendering, sub-volumes, fade, and Fog of War.

General Settings

DynamicFogProfile profile

Reference to the DynamicFogProfile ScriptableObject that defines all visual fog settings. Changing this swaps the entire fog appearance.

bool showBoundary

Draws the fog volume boundary in the Game View for debugging purposes.

bool allowRotation

When enabled, the fog volume follows the rotation of the GameObject. When disabled, the rotation is reset to identity every frame.

Fade

bool enableFade

Fades the fog in when the fade controller enters the volume and out when it leaves it. Evaluated in Play Mode only.

float fadeDistance

Width of the transition band inside the volume boundary. The fog is fully visible once the fade controller is fadeDistance units inside the volume and invisible outside it. Minimum 0.1.

Transform fadeController

The transform checked against the fog volume and sub-volumes, typically the player or the camera. If null in Play Mode, the main camera is assigned automatically.

Sub-Volumes

bool enableSubVolumes

Enables sub-volume support. When the fade controller enters a DynamicFogSubVolume, the fog profile blends to the sub-volume's profile over the sub-volume's fadeDistance. Evaluated in Play Mode only.

List<DynamicFogSubVolume> subVolumes

Optional list of allowed sub-volumes. If empty, all sub-volumes in the scene are considered. Use this to filter which sub-volumes affect this fog.

Fog of War

bool enableFogOfWar

Enables the Fog of War system, which allows clearing or restoring fog in specific world areas at runtime.

bool fogOfWarShowBoundaries

Draws the Fog of War area as a gizmo in the Scene View for debugging.

Vector3 fogOfWarCenter

World-space center of the Fog of War area. Only X and Z are used.

Vector3 fogOfWarSize

Size of the Fog of War area in world units. Only X and Z are used. Default 1024 x 1024.

int fogOfWarTextureSize

Resolution of the Fog of War texture created in Play Mode, from 32 to 2048 (rounded down to a multiple of 4). Higher values allow finer control but use more memory. Set it before the texture is created: changing it later does not resize an existing texture.

float fogOfWarRestoreDelay

Default delay in seconds (0 to 100) before cleared fog starts restoring. A value of 0 keeps the change. Used by the SetFogOfWarAlpha overloads that do not take a restore delay.

float fogOfWarRestoreDuration

Default duration in seconds (0 to 25) of the fog restoration animation. Used by the SetFogOfWarAlpha overloads that do not take a restore duration.

float fogOfWarSmoothness

Default border smoothness (0 to 1) of cleared fog areas. Higher values create softer edges. Used by the SetFogOfWarAlpha overloads that do not take a smoothness value.

bool fogOfWarBlur

Enables blur on the Fog of War texture for smoother visual transitions between cleared and fogged areas.

Texture2D fogOfWarTexture property

Gets or sets the Fog of War mask texture (alpha 0 = no fog). A custom texture must be square and readable (Read/Write enabled), otherwise an error is logged and the texture is ignored. Assigning a valid texture enables Fog of War, loads its pixels and sets fogOfWarTextureSize to its width.

Color32[] fogOfWarTextureData property

Direct access to the Fog of War pixel buffer, one Color32 per texel. The alpha channel controls fog visibility (255 = full fog, 0 = clear). Assigning an array of the same length (texture width x height) uploads it immediately, cancels pending transitions and enables Fog of War. You can also modify the returned array in place and then call UpdateFogOfWar(true).

Methods

void UpdateMaterialProperties()

Applies any changes made to the fog profile or component properties to the material. Call this after modifying profile fields at runtime.

void UpdateFogOfWar(bool forceUpload = false)

Advances the active Fog of War transitions and uploads pending changes to the GPU. It runs automatically every frame while enableFogOfWar is on. Call it with true after modifying the array returned by fogOfWarTextureData in place.

void ReloadFogOfWarTexture()

Reloads the Fog of War buffer from the current pixels of fogOfWarTexture, clears pending transitions and enables Fog of War. fogOfWarTextureSize is set to the texture width.

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

Sets the fog alpha within a circular area with a 1 second transition, using fogOfWarSmoothness, fogOfWarRestoreDelay and fogOfWarRestoreDuration. Alpha 0 = fully clear, 1 = full fog. Only the X and Z coordinates are used.

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

Sets the fog alpha within a circular area with an animated transition over the specified duration in seconds (0 = instant).

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

Sets the fog alpha with animated transition and edge smoothness control.

void SetFogOfWarAlpha(Vector3 worldPosition, float radius, float fogNewAlpha, bool blendAlpha, float duration, float smoothness, float restoreDelay, float restoreDuration)

Full-control overload. All parameters are explicit:

blendAlpha: if true, the soft border blends towards the existing alpha; if false, towards full fog duration: transition time in seconds (0 = instant) smoothness: border softness, 0 to 1 restoreDelay: seconds before fog starts restoring (0 = keep the change) restoreDuration: seconds for the restoration animation
void SetFogOfWarAlpha(Bounds bounds, float fogNewAlpha, float duration)

Sets the fog alpha within a rectangular area defined by Bounds, with animated transition.

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

Sets the fog alpha within a Bounds area with transition and edge smoothness.

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

Full-control Bounds overload with all parameters explicit.

void ResetFogOfWarAlpha(Vector3 worldPosition, float radius)

Instantly resets the fog to full opacity within a circular area and cancels the pending transitions there.

void ResetFogOfWarAlpha(Bounds bounds)

Resets fog to full opacity within a rectangular Bounds area.

void ResetFogOfWarAlpha(Vector3 position, Vector3 size)

Resets fog to full opacity within a rectangular area defined by center position and size.

void ResetFogOfWarAlpha(Vector3 position, float extentsX, float extentsZ)

Resets fog to full opacity within a rectangular area defined by center position and XZ extents.

void ResetFogOfWar(byte alpha = 255)

Resets the entire Fog of War texture and cancels all transitions. Default alpha 255 restores full fog everywhere. Use alpha 0 to clear all fog. Does nothing if the texture has not been created yet.

float GetFogOfWarAlpha(Vector3 worldPosition)

Returns the current fog alpha value at a world position (0 = clear, 1 = full fog). Returns 1 outside the Fog of War area or when there is no Fog of War texture. Useful for gameplay logic that depends on fog visibility.

DynamicFogProfile

ScriptableObject that holds all visual fog settings. Create profiles in the Project panel via Create > Dynamic Fog & Mist > Fog Profile. Multiple fog volumes can share the same profile.

Density & Range

float baseAltitude

World-space height where the fog is densest. Above it, the fog thins out exponentially according to heightSpread. Fog also renders below this height unless baseAltitudeClip is enabled.

bool baseAltitudeClip

When enabled, base altitude acts as a hard clipping plane preventing fog from rendering below it. Default: false.

float maxHeight

World-space height limit of the fog. Points above this height receive progressively less fog.

float density

Overall fog intensity multiplier (minimum 0). Higher values produce denser fog at all distances. Formerly named densityLinear; saved values are migrated automatically.

float startDistance

Distance from the camera where the fog starts (minimum 0). No fog renders closer than this distance.

float heightSpread

Vertical spread of the fog layer, from 0 to 1. Higher values produce a tall fog layer extending above baseAltitude, lower values create thin fog that hugs the ground. Formerly named densityExponential; saved values are migrated automatically.

float distanceMax

Maximum rendering distance for the fog in world units. Pixels farther than this distance from the camera receive no fog.

bool useXYZDistance

When enabled (default), uses full 3D distance for fog calculations. When disabled, uses only XZ-plane distance (ignoring vertical component).

Colors & Lighting

Color tintColor

Base tint color of the fog. The alpha channel controls overall fog opacity.

float brightness

Brightness multiplier applied to the directional light color when useSunColor is enabled.

bool useSunColor

When enabled, the fog color is multiplied by the color and intensity of the sun assigned in the Dynamic Fog Manager, dimmed when the sun goes below the horizon. When disabled, white is used.

float lightDiffusionPower

Power of the light diffusion glow around the sun direction, from 0 to 128. Higher values create a more concentrated glow. The glow is applied where no geometry is rendered (sky).

float lightDiffusionIntensity

Intensity of the light diffusion glow, from 0 to 1. A value of 0 disables the effect.

bool useVerticalGradient

Enables a vertical color gradient on the fog instead of a uniform color.

Gradient verticalGradient

The gradient used for fog coloring when useVerticalGradient is enabled. It is sampled by the vertical angle of the view direction combined with the sun elevation, from horizontal (left) to vertical (right). Its color and alpha multiply the fog color and opacity.

float dithering

Dithering intensity to reduce color banding artifacts, from 0 to 2.

Noise & Animation

float scale

Horizontal scale of the noise pattern. Higher values create larger, more spread-out noise features.

float shift

Offset added to the noise value used to mix in noiseColor. Range -1 to 1.

float turbulence

Strength of the noise displacement applied to the fog height. Higher values create more chaotic fog shapes.

float speed

Animation speed of the wind and the noise turbulence.

Vector3 direction

Wind direction for fog animation. The X and Z components scroll the noise along those world axes; Y is not used.

float noiseColorBlend

Maximum blend towards noiseColor, modulated by the noise pattern. Range 0 (only tint) to 1.

Color noiseColor

Secondary color applied to the noise pattern, blended according to noiseColorBlend.

float noiseDistanceAtten

Attenuates the noise color with distance from the camera. Range 0 (no attenuation) to 1 (noise color fades completely at the far plane). Helps reduce visual noise at far distances.

Rendering

bool boxProjection

When enabled, the fog is computed along rays parallel to the camera forward axis, using eye depth instead of the radial distance from the camera position.

bool depthClip

Hides the fog behind opaque objects: pixels where opaque geometry is closer to the camera than the fog volume boundary receive no fog. The fog is always limited by the scene depth.

int renderQueue

Render queue for the fog material. Default 3099 (transparent range). Adjust to control rendering order relative to other transparent objects.

int sortingLayerID

Sorting layer ID for the fog renderer. Controls rendering order with other sorting layers.

int sortingOrder

Sorting order within the sorting layer for the fog renderer.

Events

event OnSettingsChanged onSettingsChanged()

Raised when the profile is edited in the Inspector (Editor only). Assigning profile fields from a script does not raise it: call UpdateMaterialProperties() on the fog instead.

fog.profile.onSettingsChanged += () => {
    Debug.Log("Fog settings changed");
};

Methods

void ValidateSettings()

Clamps the numeric settings to their valid ranges and rebuilds the gradient colors from verticalGradient. Called automatically when the profile is enabled or edited in the Inspector, and by DynamicFog.UpdateMaterialProperties().

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

Interpolates all settings between two profiles, where t = 0 gives p1 and 1 gives p2. t is not clamped, so keep it between 0 and 1. Boolean and integer settings switch at 0.5 and verticalGradient is taken from p1. The result is stored in the current profile instance.

// Blend between two profiles over time
DynamicFogProfile result = ScriptableObject.CreateInstance<DynamicFogProfile>();
result.Lerp(profileA, profileB, Mathf.PingPong(Time.time, 1f));
fog.profile = result;
fog.UpdateMaterialProperties();

Code Examples

Basic Setup

using UnityEngine;
using DynamicFogAndMist2;

public class FogController : MonoBehaviour {
    public DynamicFog fog;

    void Start() {
        // Modify fog appearance at runtime
        fog.profile.density = 0.3f;
        fog.profile.tintColor = new Color(0.8f, 0.85f, 0.9f, 0.6f);
        fog.profile.speed = 0.5f;
        fog.profile.direction = new Vector3(1f, 0f, 0.5f);
        fog.UpdateMaterialProperties();
    }
}

Swap Profiles at Runtime

using UnityEngine;
using DynamicFogAndMist2;

public class WeatherSystem : MonoBehaviour {
    public DynamicFog fog;
    public DynamicFogProfile clearWeather;
    public DynamicFogProfile stormWeather;

    public void SetStorm() {
        fog.profile = stormWeather;
        fog.UpdateMaterialProperties();
    }

    public void SetClear() {
        fog.profile = clearWeather;
        fog.UpdateMaterialProperties();
    }
}

Smooth Profile Transitions

using UnityEngine;
using DynamicFogAndMist2;

public class FogTransition : MonoBehaviour {
    public DynamicFog fog;
    public DynamicFogProfile fromProfile;
    public DynamicFogProfile toProfile;
    public float transitionDuration = 3f;

    DynamicFogProfile blendProfile;
    float t;

    void Start() {
        blendProfile = ScriptableObject.CreateInstance<DynamicFogProfile>();
    }

    void Update() {
        if (t < 1f) {
            t = Mathf.Min(1f, t + Time.deltaTime / transitionDuration);
            blendProfile.Lerp(fromProfile, toProfile, t);
            fog.profile = blendProfile;
            fog.UpdateMaterialProperties();
        }
    }

    public void StartTransition() {
        t = 0f;
    }
}

Fog of War — Clear Around Player

using UnityEngine;
using DynamicFogAndMist2;

public class FogOfWarController : MonoBehaviour {
    public DynamicFog fog;
    public float clearRadius = 10f;
    public float clearDuration = 0.5f;
    public float restoreDelay = 5f;
    public float restoreDuration = 3f;

    void Update() {
        // Clear fog around player with auto-restore
        fog.SetFogOfWarAlpha(
            transform.position,
            clearRadius,
            0f,            // fully clear
            false,         // replace (don't blend)
            clearDuration,
            0.8f,          // smooth edges
            restoreDelay,
            restoreDuration
        );
    }
}

Fog of War — Read and Modify Texture Directly

using UnityEngine;
using DynamicFogAndMist2;

public class FogOfWarDirect : MonoBehaviour {
    public DynamicFog fog;

    public void ClearHorizontalStripe(int y, int height) {
        Color32[] data = fog.fogOfWarTextureData;
        int size = fog.fogOfWarTextureSize;

        for (int row = y; row < Mathf.Min(y + height, size); row++) {
            for (int col = 0; col < size; col++) {
                int idx = row * size + col;
                data[idx] = new Color32(data[idx].r, data[idx].g, data[idx].b, 0);
            }
        }

        fog.fogOfWarTextureData = data;
    }

    public void CheckVisibility(Vector3 worldPos) {
        float alpha = fog.GetFogOfWarAlpha(worldPos);
        if (alpha < 0.1f) {
            Debug.Log("Position is visible (fog cleared)");
        }
    }
}

Distance Fade with Player

using UnityEngine;
using DynamicFogAndMist2;

public class FogFade : MonoBehaviour {
    public DynamicFog fog;
    public Transform player;

    void Start() {
        fog.enableFade = true;
        fog.fadeDistance = 50f;
        fog.fadeController = player;
    }
}
Was this page helpful?