一、不使用MaterialPropertyBlock效果
每更改一次颜色会重新实例化一份材质、不能进行动态合批,当物体比较多时Drawcall会比较高
文章来源地址https://www.toymoban.com/news/detail-550059.html
文章来源:https://www.toymoban.com/news/detail-550059.html
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MaterialTest : MonoBehaviour
{
public List< MeshRenderer> list;
// Start is called before the first frame update
void Start()
{
for (int i = 0; i <list.Count ; i++)
{
if (i % 2 == 0)
{
list[i].material.color = Color.white;
}
else
{
list[i].material.color = Color.red;
}
}
}
}
二、使用MaterialPropertyBlock效果
更改颜色不会重新实例化一份材质、能进行动态合批,当物体比较多时能有效降低Drawcall提高帧率
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MaterialTest : MonoBehaviour
{
public List< MeshRenderer> list;
// Start is called before the first frame update
void Start()
{
MaterialPropertyBlock materialPropertyBlock = new MaterialPropertyBlock();
for (int i = 0; i < list.Count; i++)
{
materialPropertyBlock.SetColor("_Color", Color.white);
list[i].SetPropertyBlock(materialPropertyBlock);
}
}
}
三、使用MaterialPropertyBlock有多种颜色效果
相同颜色的物体,能够进行合批处理,示例中4个物体有两种颜色,合批后会有两个drawcall
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MaterialTest : MonoBehaviour
{
public List< MeshRenderer> list;
// Start is called before the first frame update
void Start()
{
MaterialPropertyBlock materialPropertyBlock = new MaterialPropertyBlock();
for (int i = 0; i < list.Count; i++)
{
if (i % 2 == 0)
{
materialPropertyBlock.SetColor("_Color", Color.white);
list[i].SetPropertyBlock(materialPropertyBlock);
}
else
{
materialPropertyBlock.SetColor("_Color", Color.red);
list[i].SetPropertyBlock(materialPropertyBlock);
}
}
}
}
到了这里,关于Unity之MaterialPropertyBlock优化Drawcall的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!