I’m trying unsuccesfully setup a static mesh component BEFORE spawning the actor.
I want to have the mesh already defined in GameMode in a dedicated multiplayer game, so when the clients enter the game they get the correct version right away.
I’m using DefferedSpawn in Cpp.
Before finishing the spawn, I call a custom function Init() in the actor to define the static mesh.
I did so many different tries that I don’t knowe anymore how much of problems I had.
Finally I got something to work like this:
void MyGameModeBase::SpawnSimpleActor(const FString& AssetPath, FVector Location)
{
UWorld* World = GetWorld();
const FRotator InRotation = FRotator(0.f, 0.f, 0.f);
const FVector InScale3D = FVector(1.f,1.f,1.f);
const FTransform SpawnTransform = FTransform(InRotation, Location, InScale3D);
ASimpleSMActor* SpawnActor = World->SpawnActorDeferred<ASimpleActor>(ASimpleSMActor::StaticClass(), SpawnTransform, this);
SpawnActor->Init(); // Here in this function I set the Actor Static Mesh
SpawnActor->FinishSpawning(SpawnTransform);
}
void ASimpleActor::Init(const FString& AssetPath)
{
RootComp = NewObject<USceneComponent>(this, USceneComponent::StaticClass(), TEXT("RootComponent"));
SetRootComponent(RootComp);
RootComp->RegisterComponent();
StaticMeshComp = NewObject<UStaticMeshComponent>(this, UStaticMeshComponent::StaticClass(), TEXT("StaticMeshComponent"));
if(StaticMeshComp)
{
StaticMeshComp->AttachToComponent(GetRootComponent(), FAttachmentTransformRules::KeepRelativeTransform );
StaticMeshComp->CreationMethod = EComponentCreationMethod::Instance;
InStaticMesh = LoadObject<UStaticMesh>(NULL, TEXT("/Game/Assets/Meshes/SM_SimpleCone.SM_SimpleCone"), NULL, LOAD_None, NULL);
if(InStaticMesh)
{
StaticMeshComp->SetStaticMesh(InStaticMesh);
StaticMeshComponent->RegisterComponent();
}
}
}
However, the actor always spawn on 0,0,0, regardless the Location passed to FinishSpawn function.
I found it does spawn at the correct Location if I create the Scene (Root) Component in the Actor Constructor, using CreateDefaultsuboject. So maybe it is a problem how I create the Scene Component (the Root) in the Actor Init(). However, I cannot find anywhere, no sample code how to proper set the Root Component from scratch.
For now I’ll probably change my code to replicate the Static Mesh change to relevant clients.
But I would love to know if someone knows how to setup the components BEFORE spawning the Actor. And how to make it work on a dedicated server setup.