GameCrew AIEarly access
Sign in
Unity 6optimizationCompile-verified pattern

GPU-Instanced Wind Foliage & Interactive Player Bend in Unity 6 URP

Draw thousands of swaying grass blades, reeds, or wildflowers in 1–4 draw calls using Graphics.RenderMeshInstanced, URP instanced HLSL wind gusts, tip flutter, and player-sphere pushback.

  • foliage
  • grass
  • wind
  • instancing
  • vegetation
  • rendermeshinstanced
  • vertex-shader
  • urp

When to Use & Field Best Practices

Spawning 5,000 GameObject grass tufts kills scene build time, PlayMode startup, and CPU frame rate. Modern lush meadows and Stylized vistas (*Ghost of Tsushima*, *Zelda: Breath of the Wild*) render dense ground cover at < 0.4 ms using:

  1. Pure Matrix Batches (Graphics.RenderMeshInstanced): Store Matrix4x4[] chunks of up to 1023 instances per batch on a single manager MonoBehaviour — zero per-blade GameObject, Transform, or Collider overhead.
  2. Two-Layer Vertex Wind: Combine a macro travelling wave (sin(w·p_xz - ω t)) that rolls coherent gusts across hillsides with a micro per-instance phase flutter, weighted by quadratic height h^2 so roots stay pinned to terrain.
  3. Terrain-to-Tip Color Gradient (Fake Ambient Occlusion): Darken blade bases toward the underlying ground palette and brighten tips toward warm sunlight so blades blend seamlessly into the ground mesh without shadow-map acne.
  4. Interactive Player Repulsion: Pass _InteractorPos (xyz = player feet, w = push radius) globally or on the material so blades part smoothly around the moving character.

Mathematical & Algorithmic Core

For vertex height fraction h = saturate(y_os / H):

  • Pinned Root Weight: w(h) = h^2
  • Travelling Gust + Micro Flutter: $g(p_w, t) = sin(0.22 p_x + 0.16 p_z - 2.1 t) · 0.65 + sin(0.61 p_x - 0.48 p_z - 3.9 t) · 0.35$
  • Length-Preserving Vertical Droop: When a blade bends horizontally by Δ x, drop $y$ by -0.35 \|Δ x\| so blades arc instead of stretching taller.

Engine Implementation

1. URP Instanced Wind Grass Shader (Assets/Game/Resources/Shaders/WindFoliage.shader)

Shader "Custom/WindFoliage"
{
    Properties
    {
        _RootColor ("Root Color", Color) = (0.14, 0.34, 0.18, 1.0)
        _TipColor ("Tip Color", Color) = (0.46, 0.74, 0.28, 1.0)
        _GustColor ("Sunlit Gust Tint", Color) = (0.72, 0.88, 0.38, 1.0)
        _WindParams ("DirX, DirZ, Strength, Speed", Vector) = (0.85, 0.52, 0.32, 2.1)
        _BladeHeight ("Blade Reference Height", Float) = 1.0
        _InteractorPos ("Player Feet XYZ, Radius W", Vector) = (0.0, -999.0, 0.0, 1.4)
    }
    SubShader
    {
        Tags { "RenderPipeline" = "UniversalPipeline" "RenderType" = "Opaque" "Queue" = "Geometry" }
        Pass
        {
            Name "WindFoliageForward"
            Tags { "LightMode" = "UniversalForward" }
            Cull Off
            ZWrite On

            HLSLPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma multi_compile_instancing
            #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE

            #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
            #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"

            CBUFFER_START(UnityPerMaterial)
                half4 _RootColor;
                half4 _TipColor;
                half4 _GustColor;
                float4 _WindParams;
                float _BladeHeight;
                float4 _InteractorPos;
            CBUFFER_END

            struct Attributes
            {
                float4 positionOS : POSITION;
                float3 normalOS : NORMAL;
                UNITY_VERTEX_INPUT_INSTANCE_ID
            };

            struct Varyings
            {
                float4 positionCS : SV_POSITION;
                float3 positionWS : TEXCOORD0;
                float height01 : TEXCOORD1;
                float gust01 : TEXCOORD2;
                UNITY_VERTEX_INPUT_INSTANCE_ID
            };

            Varyings vert(Attributes input)
            {
                Varyings o;
                UNITY_SETUP_INSTANCE_ID(input);
                UNITY_TRANSFER_INSTANCE_ID(input, o);

                float h = saturate(input.positionOS.y / max(0.05, _BladeHeight));
                float bendWeight = h * h;

                float3 rootWS = TransformObjectToWorld(float3(0.0, 0.0, 0.0));
                float3 posWS = TransformObjectToWorld(input.positionOS.xyz);

                float t = _Time.y * _WindParams.w;
                float gust = sin(dot(rootWS.xz, float2(0.22, 0.16)) - t) * 0.65
                           + sin(dot(rootWS.xz, float2(0.61, -0.48)) - t * 1.85) * 0.35;
                float2 windDir = normalize(_WindParams.xy + float2(1e-4, 0.0));
                float2 sway = windDir * ((gust * 0.5 + 0.5) * _WindParams.z * bendWeight);

                float3 toBlade = posWS - _InteractorPos.xyz;
                float dist = length(toBlade);
                float radius = max(0.1, _InteractorPos.w);
                if (dist < radius)
                {
                    float push = (1.0 - dist / radius);
                    float2 pushDir = normalize(toBlade.xz + float2(1e-4, 1e-4));
                    sway += pushDir * (push * push * 0.65 * bendWeight);
                }

                posWS.xz += sway;
                posWS.y -= length(sway) * 0.35;

                o.positionWS = posWS;
                o.positionCS = TransformWorldToHClip(posWS);
                o.height01 = h;
                o.gust01 = saturate(gust * 0.5 + 0.5);
                return o;
            }

            half4 frag(Varyings input) : SV_Target
            {
                UNITY_SETUP_INSTANCE_ID(input);
                float4 shadowCoord = TransformWorldToShadowCoord(input.positionWS);
                Light mainLight = GetMainLight(shadowCoord);

                float3 tip = lerp(_TipColor.rgb, _GustColor.rgb, input.gust01 * 0.45);
                float3 albedo = lerp(_RootColor.rgb, tip, input.height01);
                float shade = lerp(0.45, 1.0, mainLight.shadowAttenuation) * lerp(0.55, 1.05, input.height01);
                float3 color = albedo * mainLight.color * shade;
                return half4(color, 1.0);
            }
            ENDHLSL
        }
    }
}

2. Chunked RenderMeshInstanced Field Renderer (Assets/Game/Runtime/Rendering/InstancedFoliageField.cs)

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;

namespace Game.Rendering
{
    public sealed class InstancedFoliageField : MonoBehaviour
    {
        private const int BatchCap = 1023;
        private readonly List<Matrix4x4[]> _batches = new List<Matrix4x4[]>();
        private Mesh _bladeMesh;
        private Material _material;
        private RenderParams _renderParams;
        private Transform _interactor;

        public void Configure(Material windMaterial, IReadOnlyList<Matrix4x4> transforms, Transform interactor = null)
        {
            _bladeMesh = BuildTaperedBladeMesh(0.14f, 0.95f);
            _material = windMaterial;
            _material.enableInstancing = true;
            _interactor = interactor;
            _renderParams = new RenderParams(_material)
            {
                shadowCastingMode = ShadowCastingMode.Off,
                receiveShadows = true
            };

            _batches.Clear();
            int total = transforms.Count;
            string gpu = (SystemInfo.graphicsDeviceName ?? string.Empty).ToLowerInvariant();
            int stride = (gpu.Contains("llvmpipe") || gpu.Contains("swiftshader")) ? 3 : 1;

            var current = new List<Matrix4x4>(BatchCap);
            for (int i = 0; i < total; i += stride)
            {
                current.Add(transforms[i]);
                if (current.Count == BatchCap)
                {
                    _batches.Add(current.ToArray());
                    current.Clear();
                }
            }
            if (current.Count > 0) _batches.Add(current.ToArray());
        }

        private void Update()
        {
            if (_bladeMesh == null || _material == null) return;
            if (_interactor != null)
            {
                Vector3 p = _interactor.position;
                _material.SetVector("_InteractorPos", new Vector4(p.x, p.y, p.z, 1.35f));
            }
            for (int i = 0; i < _batches.Count; i++)
            {
                var batch = _batches[i];
                Graphics.RenderMeshInstanced(_renderParams, _bladeMesh, 0, batch, batch.Length);
            }
        }

        public static Mesh BuildTaperedBladeMesh(float width, float height)
        {
            float hw = width * 0.5f;
            var mesh = new Mesh { name = "ProceduralGrassBlade" };
            mesh.vertices = new[]
            {
                new Vector3(-hw, 0f, 0f),
                new Vector3( hw, 0f, 0f),
                new Vector3(-hw * 0.65f, height * 0.48f, 0.02f),
                new Vector3( hw * 0.65f, height * 0.48f, 0.02f),
                new Vector3(0f, height, 0.06f)
            };
            mesh.normals = new[]
            {
                Vector3.up, Vector3.up, Vector3.up, Vector3.up, Vector3.up
            };
            mesh.triangles = new[] { 0, 2, 1, 1, 2, 3, 2, 4, 3 };
            mesh.RecalculateBounds();
            return mesh;
        }
    }
}

Browser, Mobile & Software-Renderer Budgets

  • Triangle Count Per Blade: A 3-triangle 2-segment tapered blade (BuildTaperedBladeMesh) bends smoothly while keeping 4,000 instances at just 12,000 triangles across 4 draw calls.
  • No Shadow Casting on Grass: Always set ShadowCastingMode.Off on grass batches (receiveShadows = true is plenty; shadow-casting thousands of blades ruins shadow-cascade fill rate).
  • enableInstancing = true: Required on the Material instance for Graphics.RenderMeshInstanced to batch in WebGL 2.

Verification Checklist

  1. Confirm _material.enableInstancing = true is set; Unity throws an ArgumentException in PlayMode if RenderMeshInstanced receives a non-instanced material.
  2. Record a short movement clip with record_test and open the contact sheet to verify coherent travelling gusts and smooth player partings.

Official references

  • Kévin Boulanger & Fernando (GPU Gems Ch. 7 — Rendering Countless Blades of Waving Grass)
  • EricZhang / Sucker Punch (GDC 2021 — Procedural Grass in Ghost of Tsushima)
  • Unity 6 Graphics.RenderMeshInstanced API

Playable Unity 6 games made with GameCrew

Launch a real browser build using this engine and inspect its controls or fork its project tree.

Kerbside — Every push, pop and scrape is earned: a grounded skateboarding game where your feet, not a button, do the trick, and a clean landing feels like the real thing.

Kerbside

Every push, pop and scrape is earned: a grounded skateboarding game where your feet, not a button, do the trick, and a clean landing feels like the real thing.

Fjordline — Leap from a granite wall under the midnight sun and carve one unbroken wingsuit line through Norway's most dramatic landscapes, from summit to sea, skimming close enough to touch the rock.

Fjordline

Leap from a granite wall under the midnight sun and carve one unbroken wingsuit line through Norway's most dramatic landscapes, from summit to sea, skimming close enough to touch the rock.

More Unity 6 techniques

lighting

Atmospheric Height Fog, Sun Shafts & Rim-Readable Lighting in Unity 6 URP →

Three-point outdoor/interior URP lighting recipe combining directional sun + warm/cool fill, exponential height/distance fog, ACES/Neutral post-processing, and anti-darkness floors so captures never read black or washed out.

shaders

Cel-Shading, Shadow Ramps & Width-Compensated Outlines in Unity 6 URP →

Two-pass URP stylized cel shader combining main-light shadow-attenuated diffuse ramps, crisp specular/rim accents, and clip-space distance-compensated inverted-hull outlines.

physics

CharacterController Slope Projection & Floor Snap in Unity 6 →

Deterministic Unity 6 CharacterController locomotion with SphereCast ground projection, ramp stickiness, steep-slope slide, and coyote jumps.

ai

Context Steering, Telegraphed Combat & Attack-Token Encounters in Unity 6 →

Readable enemy and companion AI in Unity 6 using 8-ray context steering maps, FOV + line-of-sight hysteresis, telegraph/active/recovery state machines, and an encounter attack-token director.

Use verified techniques inside a real game

Describe your game idea for free or connect an MCP assistant to search and contribute techniques.

Learn about collaboration