Setting cbuffer floats in scripts
Hello. Trying to do a custom 2d lighting system. I'm mainly getting used to unity, i'm fine on the shader code. I'm having issues setting values in a const buffer via script. I have the const buffer...
struct LightData
{
float foregroundFactor;
float gameFactor;
float backFactor;
float minIntensity;
float maxIntensity;
float radius;
float2 pos;
float angle;
float2 direction;
};
static const int MAXLIGHTS = 64;
CBUFFER_START(PerFrame);
int layer;
LightData lights[MAXLIGHTS];
int activeLights;
CBUFFER_END
I am testing that i can set the cbuffer values with the following fragment shader code...
if(layer > 2)
{
o.r = 1;
}
o.b = lights[0].foregroundFactor;
o.g = 1;
And I am trying to set properties c# side with the following code...
int id = Shader.PropertyToID("lights[0].foregroundFactor");
GetComponent<SpriteRenderer>().material.SetFloat(id, 255.0f);
GetComponent<SpriteRenderer>().material.SetInt("layer", 3);
The layer is acknowledged in the shader, but lights[0].foregroundFactor seems to always be 0. I'm only using id for lights[0].foregroundFactor b/c I wanted to confirm the id looked fine and wasn't some obvious error value, and the id is reasonable. In addition, hasproperty("lights[0].foregroundFactor") returns true.
What am I missing that is causing lights[0].foregroundFactor to not be updated? Another thing that might be relevant is I'm using custom vertex and fragment shaders, not unity's surface/lighting system.
EDIT: I moved it to Float array, and that works. So technically I could splat out the array of structs into many arrays of struct members but that seems bad. So I guess the question is how to set struct members in cbuffers correctly.
Also, I know optimized out issues are a frequent cause of error, but I think they don't apply here b/c I'm using layer and im using lights[0].foregroundFactor, which is the first field in the first struct in the array, so the offset being used to set the val in the cbuffer should be unaffected by the rest of the lightdata struct being optimized out
Hi! Some info about that? It's correct way to setup cbuffer data like as simple shader properties? I'm simply setup variables separately and they sended on GPU as one "batch" of data to my cbuffer?
Your answer
![](https://koobas.hobune.stream/wayback/20220612124402im_/https://answers.unity.com/themes/thub/images/avi.jpg)