In another tip here, Eduardo Dias da Costa showed us how to customize materials for different game objects. This is a great practice that can save a lot of work in creating the materials. However, in cases where the objects will frequently be generated and later destroyed, 这种技术可能导致泄漏, as Unity generates a new instance of the material every time it’s modified and assigned to a Mesh Renderer. In this case, 如果您将重复使用具有相同参数的材料, 使用一个材料库是很有用的. I usually start with this generic class, and later customize if needed:
///
/// Generic material pool
///
/// A class or struct that contains the parameters for identifying and constructing a new material
public class MaterialPool {
// The definition of a function that given a T will return a new material.
// This is used when the material is inserted in the pool for the first time.
public delegate Material MaterialGenerator(T);
private Dictionary pool;
private MaterialGenerator生成器;
公共MaterialPool(MaterialGenerator生成器){
this.pool = new Dictionary();
this.generator = generator;
}
public Material GetMaterial(T) {
Material mat;
if (!pool.TryGetValue(t, out mat)) {
mat = generator(t);
pool[t] = mat;
}
return mat;
}
}
It requires two additional, customized, 元素:一个材料生成器函数, 以及提供定制材料参数的类型:
/// be careful when overriding both Equals and GetHashCode methods so that it will work correctly
///作为字典中的键
struct MaterialDef {
...
}
///从定义中生成一个新的材质
private Material MaterialGenerator(MaterialDef matDef) {
...
}
///在Start或Awake实例中设置材质池
matPool = new MaterialPool(MaterialGenerator);
/// later in the code, when needing a new material, just request it from the pool
gameObject.GetComponent().material = matPool.GetMaterial(新MaterialDef ( ... ));
A big benefit of this approach is that it enables you to separate different concerns:
- The pooling.
- The identification of what makes one material different from the other.
- 物质生成本身.
You can replace each one of these without worrying (much) about the others. Another advantage of this approach is that it allows you just to query for a material from the pool without caring whether it will generate a new one or reuse an existing one.