Skip to content

Use MaterialPropertyBlocks to change the color of materials #110

@sea212

Description

@sea212

As of now, the override of the WearNTear Highlight function within Extension.cs does copy materials and directly modify the color field of the materials:

foreach (OldMeshData oldMaterial in self.m_oldMaterials)
{
if ((bool)oldMaterial.m_renderer)
{
Material[] materials = oldMaterial.m_renderer.materials;
foreach (Material obj in materials)
{
obj.SetColor("_EmissionColor", color * 0.3f);
obj.color = color;
}
}
}

This leads to the creation of new material instances. Creating new instances is on one hand unnecessarily expensive in terms of computational time and in terms of memory (which can be neglected in that case) and on the other hand causes issues with material caching, as it is done in the following code snippet:

if (!OriginalMaterialDict.ContainsKey(originalMaterial.name))
{
OriginalMaterialDict[originalMaterial.name] = originalMaterial;
}

As new instances haven new names, this caching mechanism is not only inefficient but also prone to storing wrong original material information (such as saving materials that are colored).

Solution
Use MaterialPropertyBlocks (see unity documentation and explanatory article) to change the color of materials.
I suggest to use the ColorfulPieces mod, which provides a clean and efficient implementation, or alternatively implement it completely by yourself (example).

Notes

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions