Unity TextureArray采样

向C#中传递TextureArray

Texture2DArray _texArr = new Texture2DArray(128, 128, 5, TextureFormat.RGBA32, false, true);
for(int i = 0; i < texs.Count, i++)
{
	Texture texture = texs[i];
    Graphics.CopyTexture(texture, 0, 0, _texArr , i, 0);
}

_texArr.wrapMode = TextureWrapMode.Repeat;
_texArr.filterMode = FilterMode.Bilinear;
_texArr.Apply();
_material.SetTexture("_MyArr", _texArr);

采样TextureArray数组


Shader "Unlit/NewUnlitShader"
{
    Properties
    {
        _MyArr("Tex", 2DArray) = "" {}
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 100

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            // make fog work
            #pragma multi_compile_fog

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                UNITY_FOG_COORDS(1)
                float4 vertex : SV_POSITION;
            };

            UNITY_DECLARE_TEX2DARRAY(_MyArr);

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                //如果有缩放和偏移可以考虑使用数组传递值
                //o.uv = TRANSFORM_TEX(v.texcoord, _MainTex);
                UNITY_TRANSFER_FOG(o, o.vertex);
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                // 1为贴图数组的下表
                fixed4 baseColor = UNITY_SAMPLE_TEX2DARRAY(_MyArr, fixed3(i.uv.xy, 1));
                UNITY_APPLY_FOG(i.fogCoord, col);
                return col;
            }
            ENDCG
        }
    }
}

你可能感兴趣的:(unity,贴图,游戏引擎)