- Home /
Question by
efirdc · Jan 16, 2017 at 09:48 AM ·
shadersarraysshader programming
How to pass an array of unfixed size to a shader?
Just started learning shader programming and I can't figure out how to do this. I know how to pass an array of fixed size to a shader.
This script passes the array to the shader:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// Whenever "sizeOfShaderArray" is changed, this script will update the _Array property of the shader
public class ArrayShaderScript : MonoBehaviour {
public int sizeOfShaderArray = 20;
[ExecuteInEditMode]
void Awake()
{
InitializeArray();
}
void OnValidate()
{
InitializeArray();
}
private void InitializeArray()
{
// Initialize the array with data
float[] data = new float[sizeOfShaderArray];
for (int i = 0; i < sizeOfShaderArray; i++)
data[i] = 0.5f;
// Add the array to the material.
MaterialPropertyBlock arrayPropertyBlock = new MaterialPropertyBlock();
arrayPropertyBlock.SetFloatArray("_Array", data);
GetComponent<Renderer>().SetPropertyBlock(arrayPropertyBlock);
}
}
And this is how I define and use the array in my shader script:
sampler2D _MainTex;
float _Array[20]; // Instead of having a fixed size, I want this to be my "sizeOfShaderArray" variable in the ArrayShaderScript.
fixed4 frag (v2f i) : SV_Target
{
fixed4 col = tex2D(_MainTex, i.uv);
col *= _Array[5]; // Do stuff with array here
return col;
}
Comment
Answer by rober-psious · Jan 16, 2017 at 10:55 AM
The array initialization needs a length. You must look for other way.