Change StaticMesh runtime via C++

You can do something like this:



#include "Runtime/CoreUObject/Public/UObject/SoftObjectPtr.h"




UPROPERTY( Category="MyCategory", EditAnywhere, BlueprintReadWrite, meta=( DisplayName="My Custom Mesh", **AllowedClasses="StaticMesh"** ) )
**FSoftObjectPath **CustomMesh;




MeshForLoad = Cast<UStaticMesh>( CustomMesh.ResolveObject() );

if ( MeshForLoad == nullptr )
{
    MeshForLoad = Cast<UStaticMesh>( CustomMesh.TryLoad() );  // Load asset if not already loaded, this is slow...
}



That way people using the editor can just set the value of CustomMesh and in code you can use whatever mesh they inserted there.
Note: This is Unreal 4.20 ~ 4.22 API, in older versions this might not work at all.

2 Likes