I know I can initialize arrays via code written in C++, etc. to set arrays in a shader. What I want to know is if I can initialize the array in HLSL code instead.

For example:

float3 myArray[64] = InitializeFunction();

Is this possible?

I've tried calling this type of function in my vertex shader to set values on the array, but I get unrolling errors...

Is there a concept of a function that only runs once per frame for a shader?


1 Answer 1


No, there is no such concept. You must use CPU code to initialize your variables.

  • \$\begingroup\$ Shader programming is not my area of expertise, but shouldn't it be possible to first use a compute shader to create that array as a raw buffer and then bind that buffer to the vertex shader? stackoverflow.com/questions/19907062/… \$\endgroup\$
    – Philipp
    Dec 9, 2021 at 12:49
  • \$\begingroup\$ @Philipp sure, but you're still invoking the compute shader from the CPU side, rather than having it automatically invoked as a sort of "initial setup step" of the vertex shader, which is what I read the question to be asking. If it's just about doing the computation on the GPU, even if the CPU still has to invoke each step, then I'd say a compute shader for setup is a good solution worth sharing in an answer. \$\endgroup\$
    – DMGregory
    Dec 9, 2021 at 12:53
  • \$\begingroup\$ Thanks that's what I figured. Too bad, I would love to have had some sort of initialize call so that my shader could be distributed without the coupling to CPU side code. Thanks for the answer. \$\endgroup\$
    – jjxtra
    Dec 9, 2021 at 16:31

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .