Copying an Actor

Hi there, just starting to learn Unreal, while comming from a unity background.

I am trying to do something as simple as copying an Actor. Somehow, this piece of code causes the engine to crash.
Within AMyActor, I am trying to copy the instance of “ActorB1” which exists in the world.
The way I intepret the code is:

  1. The FindObject<AActor> finds the actor “ActorB1” and returns a pointer to that actor.
  2. SpawnActor<AActor> gets the class which forms ActorB1 and uses it to create a new instance of it.

Somehow, this piece of code causes the engine to crash, and I have no idea why.


// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "GameFramework/Actor.h"
#include "MyActor.generated.h"

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

	// Called when the game starts or when spawned
	virtual void BeginPlay() override;
	
	// Called every frame
	virtual void Tick( float DeltaSeconds ) override;

	AActor* CreateCloneOfMyActor(AActor* ExistingActor, FVector SpawnLocation, FRotator SpawnRotation);
	
};


// Fill out your copyright notice in the Description page of Project Settings.

#include "MyProject.h"
#include "MyActor.h"


// Sets default values
AMyActor::AMyActor()
{
 	// 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;

}

// Called when the game starts or when spawned
void AMyActor::BeginPlay()
{
	Super::BeginPlay();
	AActor* actorRef = FindObject<AActor>(nullptr, TEXT("ActorB1")); //Get the Actor "ActorB1" from world
	AActor* newActor = CreateCloneOfMyActor(actorRef, FVector::ZeroVector, FRotator::ZeroRotator);
}

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

}

AActor* AMyActor::CreateCloneOfMyActor(AActor* ExistingActor, FVector SpawnLocation, FRotator SpawnRotation)
{
	UWorld* World = ExistingActor->GetWorld();
	FActorSpawnParameters SpawnParams;
	SpawnParams.Template = ExistingActor;
	AActor* actor = World->SpawnActor<AActor>(ExistingActor->GetClass(), SpawnLocation, SpawnRotation, SpawnParams);
	//GEngine->AddOnScreenDebugMessage(-1, 15.0f, FColor::Red, actor->GetName());
	return actor;
}



Image of the world outliner:
351f272afeda61109d4f26f0b542ea110d86cfd3.png

Do you have details about what line the crash is on/what the crash stack is.

On the surface my best guess would be that ExistingActor is null because the FindObject is used quite dangerously. When you use nullptr as the Outer for FindObject, you are going to find an object of that name, but it is entirely possible it is a different object somewhere in the engine with that name. Using GetLevel() as the Outer in that case is likely to better target the object you want better.