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:
- The FindObject<AActor> finds the actor “ActorB1” and returns a pointer to that actor.
- 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: