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 *= 0.5f;*
// Add the array to the material.
MaterialPropertyBlock arrayPropertyBlock = new MaterialPropertyBlock();
arrayPropertyBlock.SetFloatArray(“_Array”, data);
GetComponent().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;*
}