[Unity優化]批處理04:MaterialPropertyBlock


參考鏈接:

https://blog.csdn.net/liweizhao/article/details/81937590

 

1.在場景中放一些Cube,賦予一個新材質,使用內置shader(Unlit/Color),如下圖,可以看出動態批處理生效了

 

2.掛上下面的腳本

 1 using System.Collections.Generic;
 2 using UnityEngine;
 3 
 4 public class NewBehaviourScript : MonoBehaviour
 5 {
 6     public List<MeshRenderer> list;
 7 
 8     void Start()
 9     {
10         for (int i = 0; i < list.Count; i++)
11         {
12             list[i].material.color = Color.white;
13         }
14     }
15 }

 

運行后,會發現動態批處理不生效了,因為當修改材質時,unity會生成一份材質實例,從而做到不同對象身上的材質互不影響。如下,每個Cube都有各自的材質實例

 

3.修改一下腳本

 1 using System.Collections.Generic;
 2 using UnityEngine;
 3 
 4 public class NewBehaviourScript : MonoBehaviour
 5 {
 6     public List<MeshRenderer> list;
 7 
 8     void Start()
 9     {
10         MaterialPropertyBlock materialPropertyBlock = new MaterialPropertyBlock();
11         for (int i = 0; i < list.Count; i++)
12         {
13             materialPropertyBlock.SetColor("_Color", Color.white);
14             list[i].SetPropertyBlock(materialPropertyBlock);
15         }
16     }
17 }

 

運行后,動態批處理生效了,也沒有生成新的材質實例


免責聲明!

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



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