要在自定义着色器中对纹理数组进行采样,请执行以下步骤:
要创建纹理数组材质属性,请添加 2DArray 材质属性声明。例如:
Properties
{
_MainTex ("Texture array", 2DArray) = "" {}
}
要将纹理数组设置为着色器输入,请添加 UNITY_DECLARE_TEX2DARRAY 宏。例如:
UNITY_DECLARE_TEX2DARRAY(_MainTex);
要对纹理数组的切片进行采样,请使用 UNITY_SAMPLE_TEX2DARRAY 方法。例如,对纹理数组切片 1 进行采样:
half4 frag (v2f i) : SV_Target {
float4 color = UNITY_SAMPLE_TEX2DARRAY(_MainTex, float3(0, 0, 1));
}
要对纹理数组切片的 Mipmap 级别进行采样,请使用 UNITY_SAMPLE_TEX2DARRAY_LOD 方法。例如,对纹理数组切片 1 在 Mipmap 级别 0 进行采样:
half4 frag (v2f i) : SV_Target {
float4 color = UNITY_SAMPLE_TEX2DARRAY_LOD(_MainTex, float3(0, 0, 1), 0);
}
要仅在支持纹理数组的平台上使用自定义着色器,请使用以下任一方法:
#pragma target 3.5,来指定着色器模型 3.5 及更高版本。#pragma require 2darray,来指定支持纹理数组的 GPU。以下着色器示例通过使用对象空间顶点位置作为坐标来对纹理数组进行采样,且仅在支持纹理数组的 GPU 上运行。
Shader "Example/Sample2DArrayTexture"
{
Properties
{
// Create material properties for the 2D texture array and the slices to sample
_MyArr ("Tex", 2DArray) = "" {}
_SliceRange ("Slices", Range(0,16)) = 6
_UVScale ("UVScale", Float) = 1.0
}
SubShader
{
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
// Compile the shader only on platforms that support texture arrays
#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;
// Set the z coordinate to the slice indices
o.uv.z = (vertex.z + 0.5) * _SliceRange;
return o;
}
// Set the texture array as a shader input
UNITY_DECLARE_TEX2DARRAY(_MyArr);
half4 frag (v2f i) : SV_Target
{
// Sample the texture array
return UNITY_SAMPLE_TEX2DARRAY(_MyArr, i.uv);
}
ENDCG
}
}
}