- Home /
Using Array of Structs in Shader
Hi,
I'm trying to use an array of structs within my shader. This error is thrown; "Fragment program 'frag': Struct variable '_LightDataArray' is ignored. Only instancing constant buffers can have struct variables".
Here is the relevant code;
In shader.
struct LightData
{
vector pos;
int val;
};
LightData _LightDataArray[100];
half4 frag(VertOutput i) : COLOR
{
dist = distance(i.wpos, _LightDataArray[0].pos);
val = 1/dist; // Invert distance
val = clamp(val, _AmbientColor, 1); // We only care about _AmbientColor-1
return val;
}
In C# script.
public class LightCreator : MonoBehaviour
{
public Vector4[] positions;
public Material mat;
private void Start()
{
positions[0] = new Vector4(5, 5, 5, 1);
}
private void Update()
{
mat.SetInt("_LightDataArray", positions.Length);
mat.SetVector("_LightDataArray[0].pos", positions[0]); // Does this work?
}
}
Any help would be much appreciated!
Answer by Namey5 · Sep 24, 2019 at 01:09 PM
There's quite a bit to analyse here. For one - you can't use the material "Set" functions like that. They have specific types in the function name that let you know what you are passing to the shader, and these type have to be identical in memory layout on both sides - passing an int to 'LightData' doesn't make sense. That aside, the short answer is no - you can't pass a struct array to a shader in that way. It would be better for you to instead separate the struct into individual variable arrays, i.e.
//in the shader
float3 _LightDataPos[];
float _LightDataValue[];
//in the script
mat.SetVectorArray ("_LightDataPos", positions);
It is possible to pass struct arrays to a compute shader however, using compute buffers. So if you need to process a large amount of data on the GPU, you could switch to a compute shader and pass the struct array in that way.
https://docs.unity3d.com/ScriptReference/ComputeBuffer.html
https://docs.unity3d.com/ScriptReference/ComputeShader.html
http://kylehalladay.com/blog/tutorial/2014/06/27/Compute-Shaders-Are-Nifty.html
Your answer
Follow this Question
Related Questions
Array with multiple variables in Inspector 1 Answer
How to use array in cg shader 1 Answer
Accessing struct variables 2 Answers