- Home /
Set specific value in shader array
So, I have an array in shader:
float3 _PointPositions [10];
I'm tryng to loop through it and set each element with:
material.SetVector("_PointPositions"+i.ToString(), value);
It doesn't seem to work tho and only mentions of this method I found are ~6 years old.
Note: I know of SetVectorArray, but the input array isn't always the same size, so it cannot use it as it wants to restart editor every time different size of array is passed into it.
Answer by Shrimpey · Feb 18 at 12:54 PM
If you want to use arrays, they have to be static size. So you need to use SetVectorArray and fill rest with zeros. If you want to only fill specific parts of the array, you should use buffers instead and then SetBuffer method.
You would need something like this for buffers:
StructuredBuffer<float3> _PointPositions;
and in C# you would use this method:
SetData(Array data, int managedBufferStartIndex, int computeBufferStartIndex, int count);
it should look like this:
var dataArray = new Vector3[numberOfPoints];
positionBuffer = new ComputeBuffer(numberOfPoints, sizeof(float) * 3, ComputeBufferType.Default);
positionBuffer.SetData(dataArray, dataArrayOffset, bufferOffset, numberOfValuesToFill);
material.SetBuffer("_PointPositions", positionBuffer);
So dataArray is your array of Vec3s, dataArrayOffset is integer that determines the start and numberOfValuesToFill determines the end of vector values from array to pass. bufferOffset should be the same as dataArrayOffset if buffer in shader and array in C# are the same size.
It's a rough code, but this should give you some links to look for buffer stuff. There are StructuredBuffers, RWStructuredBuffers for different Read/Write purposes, so you can read about them as well.
that works, thanks! one more question tho... Unity says the buffer should be manually released, but if I call it right after the SetBuffer method, nothing gets set, so I suppose the buffer didn't manage to set the values yet when it is released. is there a way to wait until its set so I can release it?
Release is just used after the buffer is no longer needed - so usually while quitting the game you should free up it's memory to make sure everything is fine. Also while changing scenes etc. I usually do it in OnDestroy() function.
well what im trying to do is set the points only once, after a model is loaded. so when buffer is set once, it can be released as its no longer needed and wont be used again.
just dont know where to call it.
Your answer

Follow this Question
Related Questions
How to use array in cg shader 1 Answer
Using Array of Structs in Shader 1 Answer
Add shaders into Array based on Material Array 0 Answers
GLSL shader - array of uniform const 0 Answers
Change all materials then return the old materials? 0 Answers