JDormer
JDormer

Reputation: 315

Changing MeshRenderer materials array does not update game object

I'm trying to add a material to a mesh renderer at runtime, however the new material does not appear in game. The debug log shows that the material does get added to the objRender.materials array, but in the scene there is no change.

private void updateLockMaterial()
{
        MeshRenderer objRender = GetComponentInChildren<MeshRenderer>();

        List<Material> mats = objRender.materials.ToList();
        mats.Add(Instantiate<Material>(lockMat));

        Debug.Log(objRender.materials[objRender.materials.Length-1]);    //Debugging
        objRender.materials = mats.ToArray();
        Debug.Log(objRender.materials[objRender.materials.Length - 1]);  //Debugging
}

I have tried using sharedMaterials aswell with no luck.

Upvotes: 0

Views: 666

Answers (1)

TEEBQNE
TEEBQNE

Reputation: 6275

You will want to use the Material constructor to create a new Material at runtime.

Simply replace

mats.Add(Instantiate<Material>(lockMat));

instead with

mats.Add(new Material(lockMat));

The Material doc has a lot of other useful information about materials.

Upvotes: 1

Related Questions