Search Unity

It is possible to define array size with a variable

Discussion in 'Shaders' started by MaZy, Sep 18, 2016.

  1. MaZy

    MaZy

    Joined:
    Jun 29, 2012
    Posts:
    105
    Hello is this not supported?

    const int count = 2;
    float4 _hitPosition[count];
    float _remainingTime[count];

    I get this error: non constant expression for array size at line 50 (on d3d9).

    Is this not possible?
     
  2. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,352
    You can't use a variable, but you can use a define.

    #define COUNT 2
    float myArray[COUNT];
     
    MaZy likes this.
  3. jister

    jister

    Joined:
    Oct 9, 2009
    Posts:
    1,749
    how would you set the #define in the shader by a C# script?
     
  4. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,352
    You don't. The point of a #define is that it's a constant that does not change, which is required when defining array sizes for D3D9 shaders.

    The usual solution is to just have a larger-than-you-need array size and material parameter that defines the length you care about used just for iterating. This is still quite inefficient for D3D9, so the second step is to use keywords and multi compile to have several counts defined in separate #ifdef blocks, then pick the smallest size you've defined that can do the count you need.
     
    jister likes this.