Image組件修改材質不生效的解決辦法

今天在做一個shader的時候,想說通過替換shader內的兩張材質來實現圖片切換的效果

代碼如下

void SetTextrue() {
        
        int cur = count;

        mat.SetTexture("_MainTex", Textures[cur++]);
        if (cur >= Textures.Length) {
            cur = 0;
        }
        mat.SetTexture("_MainTex2", Textures[cur]);
        count++; 
        if (count >= Textures.Length) {
            count = 0;
        }
}

切換前:

切換後

結果發現在Image上的圖片,無論我怎麼切換Image內的材質球內的材質,都沒有效果,甚至所渲染的材質,根本就不存在於材質球內。但是同一個材質球在MeshRender卻可以正確顯示(下面那個倒着的Cube)

 

之後查了很久的文檔之後,發現UGUI上都會有一個CanvasRender組件,Unity對CanvasRender的定義是這樣的

A component that will render to the screen after all normal rendering has completed when attached to a Canvas. Designed for GUI application.

這個纔是UGUI能顯示在視圖上的根源。

於是我就修改了一下代碼,設置CanvasRedner的材質,發現圖片正常切換了。

代碼就在上面的基礎上多加了一行

void SetTextrue() {
        
        int cur = count;
        mat.EnableKeyword ("_NORMALMAP");
        mat.SetTexture("_MainTex", Textures[cur++]);
        if (cur >= Textures.Length) {
            cur = 0;
        }

        mat.EnableKeyword("_NORMALMAP");
        
        mat.SetTexture("_MainTex2", Textures[cur]);
        count++; 
        if (count >= Textures.Length) {
            count = 0;
        }
        //通過修改CanvasRenderer的材質,達到修改Image的效果
        canvasRenderer.SetTexture( mat.GetTexture("_MainTex"));
    }

切換前

切換後

撒花!*★,°*:.☆\( ̄▽ ̄)/$:*.°★* 。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章