Methods Returning Arrays (in .cginc)

I think I found a way to massively optimise some of my procedurally generated meshes, but to do so I need to access what is effectively a nested array in my shaders.

So first approach, flatten the thing but I will need more than 1024 values which is likely Unitys limit for array sizes (Reference: Material.SetVectorArray array size limit? )

Instead what I am trying to do is something like this in a CG Includes file:

float4 BendAxis1 [14];
float4 BendAxis2 [14];

        float4[] GetAxis(int index)
        {
          if(index == 0)
            return BendAxis1;
         else
           return BendAxis2;
//then many more checks for other axis
        }

Problem is, the shader wont compile and doesn’t like: float4[ ] GetAxis(int index) because of “Unexpected token ‘[’”

Any idea if its possible to return an array in shaders and if so what the syntax would be?

I could probably get around this with a baked texture lookup but would be a far messier solution so would rather avoid that!

Example:

            // fill array with random data - 2..xxxx is shorthand for "float4(2,2,2,2)" etc.
            static const float4 BendAxis1 [14] = {float4(1,0,0,1), { 0.2, 0.3, 0.4, 0.5 }, 2..xxxx,3..xxxx,4..xxxx,5..xxxx,6..xxxx,0..xxxx,1..xxxx,2..xxxx,3..xxxx,4..xxxx,5..xxxx,6..xxxx};
            static const float4 BendAxis2 [14] = {float4(0,0,1,1), { 0.2, 1.0, 0.4, 0.1 }, 4..xxxx,6..xxxx,8..xxxx,0..xxxx,2..xxxx,4..xxxx,6..xxxx,8..xxxx,0..xxxx,2..xxxx,4..xxxx,6..xxxx};
            
            void GetAxis(int index, float4 a[14], float4 b[14], out float4 c[14])
            {
                if(index == 0)
                    c = a;
                else
                    c = b;
            }
           
            fixed4 frag (v2f i) : SV_Target
            {
                float4 BendAxis3 [14];
                GetAxis(0, BendAxis1, BendAxis2, BendAxis3);
                return BendAxis3[0];  // return red
               
                //GetAxis(1, BendAxis1, BendAxis2, BendAxis3);
                //return BendAxis3[0];  // return blue               
            }
1 Like

Huh didn’t think to try ‘out’. Thanks this works :smile: