報錯解決 unable to unroll loop, loop does not appear to terminate in a timely manner (994 iterations) or

在 Unity 寫 Shader 的時候,在一個循環裏面使用了 tex2D 函數,相似與下面這樣:app

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)] 特性來指定一個可能的最大值。oop

[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,那麼就能夠避免了。3d

函數簽名:code

  • 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.

既然提示說不支持迭代,那麼直接避免迭代就行了嘛。get


參考連接

Issues with shaderProperty and for-loop[via Unity Forum]:見4樓 Dolkar 的回答,很詳細了。it

相關文章
相關標籤/搜索