Version: Unity 6 Preview (6000.0)
Language : English
Create a texture array in a script
Cubemaps

Sample a texture array in a shader

Since texture arrays do not work on all platforms, shadersA program that runs on the GPU. More info
See in Glossary
need to use an appropriate compilation target or feature requirement to access them. The minimum shader model compilation target that supports texture arrays is 3.5, and the feature name is 2darray.

Use these macros to declare and sample texture arrays:

  • UNITY_DECLARE_TEX2DARRAY(name) declares a texture array sampler variable inside HLSL code.
  • UNITY_SAMPLE_TEX2DARRAY(name,uv) samples a texture array with a float3 UV; the z component of the coordinate is an array element index.
  • UNITY_SAMPLE_TEX2DARRAY_LOD(name,uv,lod) samples a texture array with an explicit mipmap level.

Examples

The following shader example samples a texture array using object space vertex positions as coordinates:

Shader "Example/Sample2DArrayTexture"
{
    Properties
    {
        _MyArr ("Tex", 2DArray) = "" {}
        _SliceRange ("Slices", Range(0,16)) = 6
        _UVScale ("UVScale", Float) = 1.0
    }
    SubShader
    {
        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            // texture arrays are not available everywhere,
            // only compile shader on platforms where they are
            #pragma require 2darray
            
            #include "UnityCG.cginc"

            struct v2f
            {
                float3 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };

            float _SliceRange;
            float _UVScale;

            v2f vert (float4 vertex : POSITION)
            {
                v2f o;
                o.vertex = mul(UNITY_MATRIX_MVP, vertex);
                o.uv.xy = (vertex.xy + 0.5) * _UVScale;
                o.uv.z = (vertex.z + 0.5) * _SliceRange;
                return o;
            }
            
            UNITY_DECLARE_TEX2DARRAY(_MyArr);

            half4 frag (v2f i) : SV_Target
            {
                return UNITY_SAMPLE_TEX2DARRAY(_MyArr, i.uv);
            }
            ENDCG
        }
    }
}
Create a texture array in a script
Cubemaps