Add Instanced Mesh

I’ve gotten a blueprint version of an InstancedStaticMesh to work, and now I want to replicate the same behavior in C++. I created a class based on an AActor, and added the following code:


Header:


UCLASS()
class RESISTOR_API AInstanceEmitter : public AActor
{
	GENERATED_BODY()
	
public:	
	// Sets default values for this actor's properties
	AInstanceEmitter();

protected:
	// Called when the game starts or when spawned
	virtual void BeginPlay() override;

public:	
	// Called every frame
	virtual void Tick(float DeltaTime) override;

	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Emitter Details")
	UStaticMesh* mesh;

	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Emitter Details")
	UMaterialInterface* material;

	UInstancedStaticMeshComponent* instancer;
	FTransform transform;
};

Source


AInstanceEmitter::AInstanceEmitter()
{
 	// Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
	PrimaryActorTick.bCanEverTick = true;

	instancer = CreateDefaultSubobject<UInstancedStaticMeshComponent>(TEXT("InstanceEmitterMeshInstancer"));

	if(instancer)
	{
		instancer->AttachTo(RootComponent);
		instancer->RegisterComponent();
		instancer->SetStaticMesh(mesh);
		instancer->SetMaterial(0, material);
		AddInstanceComponent(instancer);
	}
}

// Called when the game starts or when spawned
void AInstanceEmitter::BeginPlay()
{
	Super::BeginPlay();
	
}

// Called every frame
void AInstanceEmitter::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);

	if(instancer)
	{
		transform.SetIdentity();
		instancer->AddInstance(transform);
	}
}

I created an instance of this class in the editor, assigned the mesh and the material, and set it to tick every 1 second. I know I’m passing the same transform to every instance created, I just wanted to start by seeing something. I get nothing. I can verify with print statements that the tick routine is called once a second, and that the call to AddInstance is returning an incrementing value. But nothing is rendered.

What am I doing wrong?

Just to circle back on this, I resolved it by creating the instancer in the BeginPlay routine (using NewObject instead of CreateDefaultSubobject). I discovered this was necessary by realizing that calling GetStaticMesh on the instancer was returning null for UInstancedStaticMeshComponent created in the constructor.