Unity shader 里面使用数组

发布时间 2023-12-14 23:48:25作者: 还剩几个月

很多人不知道 Unity shader 是支持通过 C# 脚本,往 shader 脚本里写入数组的。数组的总长度似乎最大2048。注意,是所有数组的总长度加一起不能超过2048。比如你写了五个数组,每个数组的长度是100,五个数组的总长度就是500。不是哪一个数组的长度不能超过2048,是所有数组的总长度不能超过2048。

uniform float4 _Points[100];

下面是举例:

Shader "Unlit/NewUnlitShader"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
    }
    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;
            };

            sampler2D _MainTex;
            float4 _MainTex_ST;
            uniform float4 _Points[100];

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                UNITY_TRANSFER_FOG(o,o.vertex);
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                // sample the texture
                fixed4 col = tex2D(_MainTex, i.uv);
                // apply fog
                UNITY_APPLY_FOG(i.fogCoord, col);
                return col;
            }
            ENDCG
        }
    }
}

写入就和别的一样:

float[] fArray = new float[100];

material.SetFloatArray("_Points", fArray);