for loop in shader

How do i use for loops in Unity shaders? I created a shader in RenderMonkey SM3 and now trying to port it to unity but i always get:

Program 'frag_surf', profile does not support "for" statements and "for" could not be unrolled

can some body help?

2 Answers

2

Hardware shaders (running on the graphics card) don't have loops in them at all, but they can fake them, which is called "unrolling." For example, if you write:

float4 col = 0;
// combine 4 copies of the texture, shifted slightly over:
for(int i=0; i<4; i++)
  col += tex2D( sampler1, UV + float2(0, i*0.05));
col = col/4; // average all thee

The compiler (or a helpful human -- you) unrolls it into:

float4 col = 0;
// combine 3 copies of the texture, shifted slighty over:
col += tex2D( sampler1, UV);
col += tex2D( sampler1, UV + float2(0, 0.05));
col += tex2D( sampler1, UV + float2(0, 0.10));
col += tex2D( sampler1, UV + float2(0, 0.15));
col = col/3; // average all thee

A software shader (running on the CPU, simulating the graphics card,) runs slower but can do anything, including loops. I assume they are useful for ultra-processed renders.

Shader model 3.0 supports dynamic loops just fine, this is a Unity bug as far as I can tell, and a damn frustrating one at that. You can bump the shader model up to 4.0 and it will work if your hardware supports it, but AFAIK there's no actual limiting factor in the hardware that should prevent it working in shader model 3.0, just Unity being weird.

add:

#pragma target 4.0

to the top of the Pass and it should work…assuming your hardware supports shader model 4.0