Scripting Support (C#)

advanced scripting

Liquid Volume Pro 2 · Scripting Support (C#)

Class: LiquidVolume
Namespace: LiquidVolumeFX
Inherits from: MonoBehaviour (partial class)

Getting Started

Add the LiquidVolume component to any mesh object (sphere, cylinder, cube, or irregular mesh). Access it from script:

using LiquidVolumeFX;

LiquidVolume lv = GetComponent<LiquidVolume>();

// Set liquid level to 75%
lv.level = 0.75f;

// Change the primary liquid color
lv.liquidColor1 = new Color(0f, 0.5f, 1f, 0.3f);

// Force a material refresh
lv.UpdateMaterialProperties();

LiquidVolume

Liquid Settings

TOPOLOGY topology

Shape of the container. Determines how the liquid is rendered (Sphere, Cylinder, Cube, or Irregular).

DETAIL detail

Rendering detail level. Controls shader complexity and whether a flask overlay is used (Simple, SimpleNoFlask (URP/HDRP only), Default, DefaultNoFlask, Multiple, MultipleNoFlask).

float level

Fill level of the liquid, from 0 (empty) to 1 (full). In Multiple detail mode, the level is determined automatically by layer amounts and densities.

float levelMultiplier

Multiplier applied to the fill level. Range 0–1. Useful for globally scaling the liquid height.

Color liquidColor1

Primary color of the liquid. Alpha controls transparency.

Color liquidColor2

Secondary color of the liquid, used for the murkiness/deep color layer. Alpha controls transparency.

Color liquidRimColor

Adds a colored rim effect to the liquid surface edge. Alpha controls the intensity.

float liquidRimPower

Controls the sharpness of the liquid rim effect. Range 0.1–4.

float liquidScale1

Scale factor for the primary liquid noise pattern. Range 0.1–4.85.

float liquidScale2

Scale factor for the secondary liquid noise pattern. Range 2–4.85.

float alpha

Global opacity of the liquid. Range 0–1. Affects both liquid colors, smoke, and foam.

float finalAlphaMultiplier

An additional final alpha multiplier applied to the rendered output. Range 0–1.

Color emissionColor

Emission (self-illumination) color added to the liquid.

float murkiness

Controls how opaque or murky the liquid appears. Range 0–1.

float turbulence1

Intensity of the primary wave turbulence on the liquid surface. Range 0–1.

float turbulence2

Intensity of the secondary wave turbulence on the liquid surface. Range 0–1.

float frecuency

Frequency of the wave oscillation. Higher values produce more rapid oscillations.

float speed

Speed of the liquid animation. Range 0–2.

float sparklingIntensity

Intensity of the sparkling highlights on the liquid surface. Range 0–5.

float sparklingAmount

Amount of sparkling highlights. Range 0–1.

float deepObscurance

Controls how much the liquid darkens with depth. Range 0–10.

bool ditherShadows

Enables dithered shadow attenuation based on liquid alpha, producing softer shadow transitions.

float ditherStrength

Strength of the dithering pattern applied to reduce color banding. Range 0–1.

int noiseVariation

Selects between different 3D noise textures for liquid and foam rendering. Range 1–3.

Multiple Layers

LiquidLayer[] liquidLayers

Array of liquid layers for the Multiple detail mode. Each layer has its own amount, density, color, murkiness, scale, viscosity, and bubbles opacity.

int MAX_LAYERS read-only

Maximum number of layers supported in Multiple detail mode. Constant value: 16.

int smoothContactSurface

Smoothing radius for contact surfaces between adjacent layers. Range 0–16.

float layersAdjustmentSpeed

Global speed at which layers animate when their values change. Range 0.001–10.

bool layersAdjustmentCompact

When enabled, layers are compacted to eliminate vertical gaps between them during animation.

Foam

Color foamColor

Color and opacity of the foam layer. Alpha controls visibility.

float foamScale

Scale of the foam noise pattern. Range 0.01–1.

float foamThickness

Vertical thickness of the foam layer. Range 0–0.1.

float foamDensity

Density of the foam pattern. Range −1 to 1. Lower values produce sparser foam.

float foamWeight

Controls the weight/heaviness of the foam, affecting how it settles. Range 4–100.

float foamTurbulence

Intensity of turbulence applied to the foam layer. Range 0–1.

bool foamVisibleFromBottom

Whether the foam layer is visible when viewed from below.

int foamRaySteps

Number of raymarching steps used to render the foam. Higher values improve quality at the cost of performance.

Texture3D foamNoiseTexture

Optional custom 3D noise texture for the foam. If null, the default noise texture is used.

Bubbles

int bubblesAmount

Number of bubbles to generate inside the liquid.

int bubblesSizeMin

Minimum bubble size in pixels. Range 1–16.

int bubblesSizeMax

Maximum bubble size in pixels. Range 1–16.

float bubblesScale

Overall scale of the bubbles.

float bubblesBrightness

Brightness multiplier for the bubbles.

float bubblesVerticalSpeed

Vertical rising speed of the bubbles.

int bubblesSeed

Random seed used for bubble placement. Changing this generates a different bubble pattern.

Smoke

bool smokeEnabled

Enables or disables the smoke/vapor effect above the liquid surface.

Color smokeColor

Color and opacity of the smoke. Alpha controls visibility.

float smokeScale

Scale of the smoke noise pattern. Range 0.01–1.

float smokeBaseObscurance

Base obscurance (opacity) of the smoke at its densest point. Range 0–10.

float smokeHeightAtten

Controls how quickly the smoke fades with height above the liquid surface. Range 0–10.

float smokeSpeed

Animation speed of the smoke. Range 0–20.

int smokeRaySteps

Number of raymarching steps used to render the smoke. Higher values improve quality at the cost of performance.

Scattering

bool scatteringEnabled

Enables sub-surface light scattering for the liquid.

int scatteringPower

Exponent for the scattering falloff. Range 1–16. Higher values produce a tighter, more focused scattering highlight.

float scatteringAmount

Intensity of the scattering effect. Range 0–10.

Texture & Bump Mapping

Texture2D bumpMap

Normal map texture applied to the liquid surface for bump mapping.

float bumpStrength

Intensity of the bump map effect. Range 0–1.

float bumpDistortionScale

Scale of the bump distortion pattern. Range 0–10.

Vector2 bumpDistortionOffset

UV offset for the bump distortion pattern.

Texture2D distortionMap

Distortion texture applied to the liquid surface.

float distortionAmount

Intensity of the distortion effect. Range 0–10.

Texture2D texture

Custom texture applied to the liquid surface (e.g., a label or pattern).

Vector2 textureScale

UV tiling scale for the custom texture.

Vector2 textureOffset

UV offset for the custom texture.

Refraction & Rendering

bool refractionBlur

Enables background blurring through the flask to simulate glass refraction.

float blurIntensity

Intensity of the refraction blur effect. Range 0–1.

int liquidRaySteps

Number of raymarching steps used to render the liquid. Higher values improve quality at the cost of performance.

int renderQueue

Render queue value for the liquid material. Default is 3001 (transparent).

Cubemap reflectionTexture

Cubemap used for reflection on the liquid surface.

float glossinessInternal

Internal glossiness of the liquid material. Range 0–1.

bool allowViewFromInside

When enabled, the liquid is rendered correctly when the camera is inside the container.

bool depthAware

Enables depth-aware rendering for irregular containers, clipping the liquid against scene geometry.

float depthAwareOffset

Depth offset used for depth-aware rendering to fine-tune clipping.

bool depthAwareCustomPass

Enables a custom depth pre-pass for more accurate front-face depth when using a parent container mesh.

float doubleSidedBias

Bias for double-sided rendering. Range 0–5.

float backDepthBias

Bias applied to back-face depth calculations. Minimum 0.

Material liqMat

Reference to the current liquid material instance used for rendering. Assigned automatically.

Renderer mr

Reference to the Renderer component (MeshRenderer or SkinnedMeshRenderer). Assigned automatically.

static bool useFPRenderTextures read-only

Indicates whether floating-point render textures are enabled (compile-time setting).

static bool FORCE_GLES_COMPATIBILITY

When set to true, forces OpenGL ES compatibility mode, using texture-based layer data instead of shader arrays.

Lighting

bool useLightColor

Uses the assigned directional light's color to tint the liquid.

bool useLightDirection

Uses the assigned directional light's direction for day/night cycle effects on the liquid.

Light directionalLight

Reference to a directional light used for lighting calculations. Enables light color and direction features.

Flask & Container

Material flaskMaterial

Material used for the flask/container overlay. Only used in detail modes that include a flask.

float flaskThickness

Thickness of the flask wall, inset from the mesh surface. Range 0–1.

Physics & Buoyancy

bool reactToForces

When enabled, the liquid reacts to movement and acceleration of the container with inertia-driven waves.

float physicsMass

Mass of the liquid for physics calculations. Higher values make the liquid less reactive to forces. Minimum 0.1.

float physicsAngularDamp

Damping factor for angular oscillation caused by forces. Range 0–0.5.

bool ignoreGravity

When enabled, the liquid ignores world gravity direction and stays relative to the object's local up axis.

LEVEL_COMPENSATION rotationLevelCompensation

Method used to maintain consistent liquid volume when the container is rotated (None, Fast, or Accurate).

Mesh & Volume

bool fixMesh

Enables mesh correction (center pivot and/or close mesh) to fix imported models that are not centered.

Mesh originalMesh

Reference to the original mesh before any fixMesh corrections are applied.

Vector3 originalPivotOffset

The position offset applied when the mesh pivot was centered, used to restore the original position.

Vector3 pivotOffset

Manual offset applied to the mesh pivot when fixMesh is enabled.

bool autoCloseMesh

When enabled along with fixMesh, generates a convex hull to close open meshes so liquid does not leak.

bool limitVerticalRange

When enabled, constrains the liquid rendering to a vertical subrange of the container defined by upperLimit and lowerLimit.

float upperLimit

Upper vertical limit of the liquid range as a factor of the mesh extents. Range 0–1.5.

float lowerLimit

Lower vertical limit of the liquid range as a factor of the mesh extents. Range −1.5 to 1.5.

int subMeshIndex

Index of the sub-mesh on which the liquid material is assigned. Set to −1 for automatic detection.

Vector3 extentsScale

Scales the effective extents of the container without changing the transform scale. Useful for fine-tuning liquid bounds.

float liquidSurfaceYPosition read-only

Returns the vertical position in world space of the liquid surface.

bool requireLayersUpdate

Set to true to force a layer recalculation on the next frame.

bool requireBubblesUpdate

Set to true to force a bubble texture regeneration on the next frame.

Point Lights

bool pointLightsEnabled

Enables animated point light effects inside the liquid (up to 6 lights).

PointLightParams[] pointLightParams

Array of point light configuration parameters (max 6). Each entry controls position, movement, color, intensity, and range.

float pointLightsScatteringAmount

Scattering amount used by point lights. Default 0.8.

float pointLightsIntensity

Global intensity multiplier for all point lights. Default 1.

float pointLightInsideAtten

Attenuation factor for point light intensity when the camera is inside the container.

Stencil

int stencilRef

Stencil buffer reference value used by the liquid shader.

CompareFunction stencilComp

Stencil comparison function. Default: Always.

StencilOp stencilPass

Stencil operation performed when the stencil test passes. Default: Keep.

StencilOp stencilFail

Stencil operation performed when the stencil test fails. Default: Keep.

StencilOp stencilZFail

Stencil operation performed when the stencil test passes but the depth test fails. Default: Keep.

Debug & Compare

bool debugSpillPoint

When enabled, displays a visual gizmo at the computed spill point of the container.

bool irregularDepthDebug

Enables debug visualization of the irregular topology depth buffer.

bool depthAwareCustomPassDebug

Enables debug visualization of the custom depth pre-pass.

Events

event PropertiesChangedEvent onPropertiesChanged(LiquidVolume lv)

Fired whenever material properties are updated. Use this to react to any property change on the liquid.

Methods

void UpdateMaterialProperties()

Schedules a full material property update. In play mode, the update happens on the next frame; in edit mode, it executes immediately.

void UpdateLayers(bool immediate = false)

Triggers a recalculation of all liquid layers. Pass true to force an immediate update instead of waiting for the next frame.

void Redraw()

Resets all layer base levels and current amounts, then triggers a full material update. Useful after significant changes to layers.

void MoveToLiquidSurface(Transform transform, BuoyancyEffect effect, Transform root = null, float dampen = 0.8f)

Moves a floating object to the liquid surface. The effect parameter controls the buoyancy style: Simple (position only, flat), PositionOnly (position with turbulence), or PositionAndRotation (full buoyancy with tilt, requires a collider and a root transform).

bool GetSpillPoint(out Vector3 spillPosition, float apertureStart = 1f)

Computes the approximate point where liquid would start spilling over the flask rim when rotated. Returns true if a spill point is detected. The apertureStart parameter (0–1) defines where the flask opening begins.

bool GetSpillPoint(out Vector3 spillPosition, out float spillAmount, float apertureStart = 1f, LEVEL_COMPENSATION rotationCompensation = LEVEL_COMPENSATION.None)

Extended overload that also outputs the spillAmount (difference in liquid volume/level beyond the spill point). The rotationCompensation parameter controls how spillAmount is calculated: None returns a level difference, Fast and Accurate return volume differences.

float GetMeshVolumeWS()

Returns the total volume of the mesh in world space using accurate mesh slicing.

float GetMeshVolumeWSFast()

Returns the total volume of the mesh in world space using a fast approximation method.

float GetMeshVolumeUnderLevel(float level01, float yExtent)

Returns the approximate mesh volume below the given fill level (0–1 range) using accurate mesh slicing. The yExtent is the vertical half-extent of the renderer bounds.

float GetMeshVolumeUnderLevelFast(float level01, float yExtent)

Fast approximation of the mesh volume below the given fill level (0–1 range). Uses vertex clamping instead of mesh slicing.

float GetMeshVolumeUnderLevelWS(float level)

Returns the approximate mesh volume below the given world-space Y position using accurate mesh slicing.

float GetMeshVolumeUnderLevelWSFast(float level)

Fast approximation of the mesh volume below the given world-space Y position.

void BakeRotation()

Applies the current transform rotation and scale to the mesh vertices and resets the transform to identity. Required for imported models that come with a baked rotation.

void CenterPivot()

Computes the geometric center of all vertices and repositions them so the pivot is at the model center.

void CenterPivot(Vector3 offset, bool closeMesh)

Centers the mesh pivot with an additional manual offset. When closeMesh is true, a convex hull is generated to close the mesh.

void RefreshMeshAndCollider()

Clears the mesh cache and refreshes the MeshCollider if present. Call after modifying the mesh externally.

void ClearMeshCache()

Clears the static mesh vertex cache shared across all LiquidVolume instances.

void SetLayerDensity(int layerIndex, float newDensity, bool keepVolume)

Changes the density of a specific layer. When keepVolume is true, the layer amount is adjusted proportionally to maintain the same visual volume.

void PointLightsRandomize()

Randomizes all point light parameters (position, color, intensity, speed, range).

void CopyFrom(LiquidVolume lv)

Copies all visual settings from another LiquidVolume instance to this one. Does not copy mesh or transform data.

Code Examples

Fill Animation

using UnityEngine;
using LiquidVolumeFX;

public class FillAnimation : MonoBehaviour {
    LiquidVolume lv;
    float targetLevel = 1f;

    void Start() {
        lv = GetComponent<LiquidVolume>();
        lv.level = 0f;
    }

    void Update() {
        lv.level = Mathf.MoveTowards(lv.level, targetLevel, Time.deltaTime * 0.2f);
    }
}

Pouring Detection

using UnityEngine;
using LiquidVolumeFX;

public class PourDetection : MonoBehaviour {
    LiquidVolume lv;

    void Start() {
        lv = GetComponent<LiquidVolume>();
    }

    void Update() {
        Vector3 spillPos;
        float spillAmount;
        if (lv.GetSpillPoint(out spillPos, out spillAmount)) {
            Debug.Log("Spilling at " + spillPos + " amount: " + spillAmount);
            // Reduce liquid level proportionally
            lv.level -= spillAmount * Time.deltaTime;
        }
    }
}

Buoyancy / Floating Object

using UnityEngine;
using LiquidVolumeFX;

public class FloatingObject : MonoBehaviour {
    public LiquidVolume liquidVolume;

    void Update() {
        if (liquidVolume != null) {
            liquidVolume.MoveToLiquidSurface(
                transform,
                BuoyancyEffect.PositionOnly
            );
        }
    }
}

Multiple Layers

using UnityEngine;
using LiquidVolumeFX;

public class LayeredDrink : MonoBehaviour {
    void Start() {
        LiquidVolume lv = GetComponent<LiquidVolume>();
        lv.detail = DETAIL.Multiple;

        lv.liquidLayers = new LiquidVolume.LiquidLayer[3];

        // Heavy red layer at bottom (high density)
        lv.liquidLayers[0].amount = 0.3f;
        lv.liquidLayers[0].density = 3f;
        lv.liquidLayers[0].color = new Color(1f, 0f, 0f, 0.5f);
        lv.liquidLayers[0].murkColor = new Color(0.5f, 0f, 0f, 1f);
        lv.liquidLayers[0].murkiness = 0.8f;
        lv.liquidLayers[0].scale = 0.3f;
        lv.liquidLayers[0].viscosity = 0.5f;
        lv.liquidLayers[0].adjustmentSpeed = 1f;
        lv.liquidLayers[0].bubblesOpacity = 1f;

        // Medium green layer (medium density)
        lv.liquidLayers[1].amount = 0.2f;
        lv.liquidLayers[1].density = 2f;
        lv.liquidLayers[1].color = new Color(0f, 1f, 0f, 0.4f);
        lv.liquidLayers[1].murkColor = new Color(0f, 0.5f, 0f, 1f);
        lv.liquidLayers[1].murkiness = 0.5f;
        lv.liquidLayers[1].scale = 0.3f;
        lv.liquidLayers[1].viscosity = 1f;
        lv.liquidLayers[1].adjustmentSpeed = 1f;
        lv.liquidLayers[1].bubblesOpacity = 1f;

        // Light blue layer on top (low density)
        lv.liquidLayers[2].amount = 0.15f;
        lv.liquidLayers[2].density = 1f;
        lv.liquidLayers[2].color = new Color(0f, 0.5f, 1f, 0.3f);
        lv.liquidLayers[2].murkColor = new Color(0f, 0.25f, 0.5f, 1f);
        lv.liquidLayers[2].murkiness = 0.3f;
        lv.liquidLayers[2].scale = 0.3f;
        lv.liquidLayers[2].viscosity = 1f;
        lv.liquidLayers[2].adjustmentSpeed = 1f;
        lv.liquidLayers[2].bubblesOpacity = 1f;

        lv.UpdateLayers(true);
    }
}

Property Change Listener

using UnityEngine;
using LiquidVolumeFX;

public class LiquidListener : MonoBehaviour {
    LiquidVolume lv;

    void OnEnable() {
        lv = GetComponent<LiquidVolume>();
        lv.onPropertiesChanged += OnLiquidChanged;
    }

    void OnDisable() {
        lv.onPropertiesChanged -= OnLiquidChanged;
    }

    void OnLiquidChanged(LiquidVolume sender) {
        Debug.Log("Liquid surface Y: " + sender.liquidSurfaceYPosition);
    }
}
Was this page helpful?