Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

How to set constant buffer in a compute shader

Discussion in 'Scripting' started by Shiv2k3, Feb 5, 2022.

  1. Shiv2k3

    Shiv2k3

    Joined:
    Jun 30, 2019
    Posts:
    118
    This is my buffer:

    statesB = new ComputeBuffer(total, size, ComputeBufferType.Constant);


    This is how I'm setting the variable in the compute shader :

    statesCS.SetConstantBuffer("states", statesB, 0, statesB.count * statesB.stride)


    This is how I'm defining my buffer in HLSL :

    Code (CSharp):
    1. cbuffer StaticVariables
    2. {
    3.     int size;
    4.     float rendDist;
    5.     RWStructuredBuffer<Chunk> states;
    6. }
    I also have extra variables that don't change often in there

    This is the error I get :

    Property (states) at kernel index (0) is not set
     
  2. esgnn

    esgnn

    Joined:
    Mar 3, 2020
    Posts:
    38
    I am not familiar with intricacies of constant buffers, is it allowed to hold another buffer? What happens if you move states out of the cbuffer?
     
  3. Shiv2k3

    Shiv2k3

    Joined:
    Jun 30, 2019
    Posts:
    118
    I tested it and I can't have a cbuffer in a cbuffer, it gives me a syntax error, and if I move states out of the buffer and fill in the states with the normal SetBuffer() it works, but I don't want that because I need to read data back from states every few seconds so I need it to be constant.
     
  4. Shiv2k3

    Shiv2k3

    Joined:
    Jun 30, 2019
    Posts:
    118
    After some testing I have come to the conclusion that you just can't use constant buffers with unity in compute shader, and the best thing to do is to set the buffer as uniform and use SetBuffer() to set that buffer.
     
  5. esgnn

    esgnn

    Joined:
    Mar 3, 2020
    Posts:
    38
    You can read data back to a StructuredBuffer. Why does it have to be a constant buffer?
     
  6. Shiv2k3

    Shiv2k3

    Joined:
    Jun 30, 2019
    Posts:
    118
    I guess I don't but then again maybe making it constant could be more performant is my thought process, and the thing is I need to make a NEW compute buffer with 4096 elements every few seconds if I don't make it constant or uniform, and so I've now gone ahead and done "uniform RWStructuredBuffer<Chunk> states" and I only need to create the buffer once and dispose it when the game ends and it seems to have cut down a bit of the lag.
     
  7. ashzhu

    ashzhu

    Joined:
    Jul 4, 2022
    Posts:
    3
    hi , i met same problem ,i did't not get errors, but the values always zero,just like this :https://forum.unity.com/threads/is-computeshader-setconstantbuffer-working.1258287/, i wonder know how to use setbuffer method? pls give me an example?