报错解决 unable to unroll loop, loop does not appear to terminate in a timely manner (994 iterations) or unrolled loop is too large, use the [unroll(n)] attribute to force an exact higher number

在 Unity 写 Shader 的时候,在一个循环里面使用了 tex2D 函数,类似与下面这样:

fixed2 center = fixed2(0.5,0.5);
fixed2 uv = i.uv - center;
for (fixed j = 0; j < _Strength; j++) {
    c1 += tex2D(_MainTex,uv*(1 - 0.01*j) + center).rgb;
}

打apk没什么问题,但是打win版本的时候有个报错

unable to unroll loop, loop does not appear to terminate in a timely manner (994 iterations) or unrolled loop is too large, use the [unroll(n)] attribute to force an exact higher number
can't use gradient instructions in loops with break

解决方案1.

错误提示上说了,没有办法对循环进行展开,因为展开的迭代次数太多了,快到一千次了,请使用 [unroll(n)] 特性来指定一个可能的最大值。

[unroll(88)]
fixed2 center = fixed2(0.5,0.5);
fixed2 uv = i.uv - center;
for (fixed j = 0; j < _Strength; j++) {
    c1 += tex2D(_MainTex,uv*(1 - 0.01*j) + center).rgb;
}

解决方案2.

由于 tex2D 函数需要确定 LOD ,即所使用的纹理层,这才必须 unroll,如果直接使用能够指定 LOD 的 tex2Dlod,那么就可以避免了。

函数签名:

  • tex2D( Sampler, IN.Texture );
  • tex2Dlod( Sampler, float4( IN.Texture, 0.0f, 0.0f ) );
fixed4 center = fixed4(.5,.5,0,0);
fixed4 uv = fixed4(i.uv,0,0) - center;
            
for (fixed j = 0; j < _Strength; j++) {
    c1 += tex2Dlod(_MainTex,uv*(1 - 0.01*j) + center).rgb;
}
            

解决方案3.

既然提示说不支持迭代,那么直接避免迭代就好了嘛。


参考链接

Issues with shaderProperty and for-loop[via Unity Forum]:见4楼 Dolkar 的回答,很详细了。

你可能感兴趣的:(报错解决 unable to unroll loop, loop does not appear to terminate in a timely manner (994 iterations) or unrolled loop is too large, use the [unroll(n)] attribute to force an exact higher number)