Instanced Static Mesh Not Appearing

I’m trying to create an instanced static mesh, and I’m not sure I’m doing it right. The following code is in a ‘Creator’ component that is supposed to spawn MyObject at the origin…

Creator.h

UPROPERTY(EditAnywhere)
		TSubclassOf<class AActor> ToSpawn; // Set this to MyObject

UPROPERTY(EditAnywhere)
		UStaticMesh* SuperMesh; // Set this to the mesh

Creator.cpp

// Other things

UInstancedStaticMeshComponent *ISMComp = NewObject<UInstancedStaticMeshComponent>(ToSpawn);

UWorld* const World = GetWorld();
	if (!World) return;

ISMComp->RegisterComponent();
	ISMComp->SetStaticMesh(SuperMesh);
	ISMComp->SetFlags(RF_Transactional);

FRotator rotator = FRotator(0.f, 0.f, 0.f);
	FVector spawnLocation = FVector(0.f, 0.f, 0.f);
	FActorSpawnParameters spawnParams;

AMyObject* Obj = World->SpawnActor<AMyObject>(ToSpawn, spawnLocation, rotator, spawnParams);

Obj->AddInstanceComponent(ISMComp);

Anyway, it compiles, but no object appears…

Okay, so I’ve rewritten the code as follows:

// Spawn Parameters

AMyObject* Obj = World->SpawnActor<AMyObject>(ToSpawn, spawnLocation, rotator, spawnParams);

ISMComp = NewObject<UInstancedStaticMeshComponent>(Obj);

ISMComp->RegisterComponent();
ISMComp->SetStaticMesh(SuperMesh);
Obj->AddInstanceComponent(ISMComp);

This compiles, but the mesh does not appear in game. If I find the actor while playing in the world outliner and click on the component “instancedStaticMeshComponent_0”, the ‘Instances’ section says there are ‘0 array elements’. If I add one there, the mesh appears… this makes me think I’m missing something.

Oh! That’s because you haven’t told it to add any instances. Now that your component is created, you can do something like this:

FTransform InstanceTransform;
InstanceTransform.SetLocation(FVector::ZeroVector);
InstanceTransform.SetRotation(FQuat::Identity);

ISMComp->AddInstance(InstanceTransform);

You need to create and register your component after spawning the actor you’re trying to attach it to. You’ll also need to pass in “Obj” instead of “ToSpawn” to the call to “NewObject” when creating the component.