Updating StaticMesh on StaticMeshComponent and updating materials to new mesh

I have Actors that I use as building blocks in my game which each have a static mesh component.

Each time I initialize one of these actors, I replace the static mesh materials with MaterialInstanceConstant’s (this is so I can manipulate the materials to show damage etc):



simulated function PreBeginPlay()
{
    for (i=0; i<Mesh.GetNumElements(); i++) {
        mat = Mesh.StaticMesh.GetMaterial(i);
        MaterialInstances.AddItem(Mesh.CreateAndSetMaterialInstanceConstant(i));
    }
    super.PreBeginPlay();
}


I am now trying to update the StaticMesh of the static mesh component during gameplay:



Mesh.SetStaticMesh(newMesh)


However the new mesh will always acquire the MaterialInstanceConstant’s set for the previous mesh.

How can I get the materials from the new mesh, so I can reset them as MaterialInstanceConstant’s?

Hope that makes sense. Thanks in advance.

I don’t know why the new mesh would automatically take the material from the old mesh. But I think the way I would have to work around it is keeping a reference to what the default material should be, and then apply it right after creating the new static mesh component.

I solved it by doing this:



simulated private function SetMaterialInstances(optional StaticMeshComponent getMatsFromThisMeshComp) {
    local int i;
    local MaterialInstanceConstant instance;

    //Doing it this way, we can grab the materials from the newly set mesh and reapply them as MaterialInstanceContants. 
    getMatsFromThisMeshComp = getMatsFromThisMeshComp != none ? getMatsFromThisMeshComp : Mesh;

    MaterialInstances.Length = 0;
    //Create a material instance for each of the mesh materials, so we can update params on them through script (like showing crack for damage).
    for (i=0; i<getMatsFromThisMeshComp.GetNumElements(); i++) {
        // Create the material instance.
        instance = new(self) class'MaterialInstanceConstant';
        instance.SetParent(getMatsFromThisMeshComp.GetMaterial(i));
        MaterialInstances.AddItem(instance);
        Mesh.SetMaterial(i, instance);
    }
}

simulated function SetNewStaticMesh(StaticMesh newMesh)
{
    Mesh.SetStaticMesh(newMesh);

    TempMeshComp.SetStaticMesh(newMesh);

    //Send the TempMeshComp, so we can generate fresh MaterialInstanceConstants (otherwise it ends up using the ones generated for the previous Mesh comp).
    SetMaterialInstances(TempMeshComp);
}



I think you could also be able to get TheMesh.default.Material ?