在Unity中,默认情况下对同一个预制体创建出来的不同实例,
是公用同一个Material
以及Shader
的,
因此对一个实例的Shader属性修改后,
别的实例也会产生相应修改,
有种Shader的参数是静态的感觉。
而如果需要不同实例使用不同的材质着色器参数时,
就需要使用材质属性块MaterialPropertyBlock()
。
性能分析可以看这一篇,还是优化挺多的。
https://www.jianshu.com/p/eff18c57fa42
使用方式也很简单:
prop = new MaterialPropertyBlock();
GetComponent<Renderer>().GetPropertyBlock(prop);
prop.SetFloat("_CircleEdge", initEdgeSize);
GetComponent<Renderer>().SetPropertyBlock(prop);
其中第一、二行只需要执行一次,
后面就用三、四动态修改着色器参数了。
例
用上一节讲圆环的具体实例,
固定各个大小不同的圆环的环宽值。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FixedEdgeWidth : MonoBehaviour
{
public float initEdgeSize = 0.04f;
float rate;
MaterialPropertyBlock prop;
void Start()
{
rate = initEdgeSize * transform.localScale.x;
prop = new MaterialPropertyBlock();
GetComponent<Renderer>().GetPropertyBlock(prop);
prop.SetFloat("_CircleEdge", initEdgeSize);
GetComponent<Renderer>().SetPropertyBlock(prop);
}
void Update()
{
prop.SetFloat("_CircleEdge", rate / transform.localScale.x);
GetComponent<Renderer>().SetPropertyBlock(prop);
}
}