Trouble setting material on a UStaticMesh*, what am I doing wrong

On my actor I have a UStaticMesh as property like this:

UPROPERTY( EditAnywhere, BlueprintReadOnly, Category = TileMap, DisplayName = "Tile Mesh" )
UStaticMesh* m_TileMesh;

At runtime I assign a dynamic material to the mesh and change a few parameters. Then I set it as the mesh in an instanced static mesh component and make lots of them.

This kind of works. The first time I play in the editor everything renders ok, and the second time it’s broken. When I inspect the mesh, I see that my dynamic material has been set to the actual mesh uasset, not just the PIE version of the mesh.

I must be doing something fundamentally wrong here. Should I not just have a UStaticMesh pointer as the property?

Extra details:
I initially assigned the material with a simple ->SetMaterial() call, but then realized that’s editor only and I need to do it at runtime. Now I use:

StaticMesh->GetStaticMaterials()[0].MaterialInterface = m_pDynTerrainMaterial

I’ve tried making a runtime copy of the static mesh using:

m_pDynStaticMesh = NewObject<UStaticMesh>( this, m_TileMesh->GetClass(), TEXT( "DynStaticMesh" ), RF_NoFlags, m_TileMesh );

That works in the editor, but not in a packaged build. If making a copy of the mesh is the way to go, please let me know how to properly initialize it. I’ve tried a bunch of combinations of initialization calls with no luck, and many of them are editor only.

Thanks!

I realized reason the mesh doesn’t work the second time I play in editor was that I was getting the material from the mesh to create the dynamic material, and on the second play it was grabbing the old (deleted?) dynamic material that got saved to the mesh last session.

I’m working around this by keeping a separate pointer to the material, so I can always grab it and apply it to the mesh, and that works in editor and packaged. It’s still saving a dynamic material to the mesh every time I play in editor though, which feels wrong, and I’d love to know the proper way to set this up.