報錯解決 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 的回答,很詳細了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM