Spawn Actor From Class Custom Function?

I want to create a virtual function that I will call any time and anywhere to spawn an actor from ActorClass , the idea i got from blueprints where we call a node and in C++ I want to add the same functionality have a function that i will call and it will take some parameters to spawn actor from class.

Note this this just an idea and I believe this is possible to achieve :smiley:

Example: may contain mistakes, but you will get the idea what I am talking about.
also I used blueprint library as I donโ€™t know other way.

MyGameMode.h

virtual void SpawnActorFromClass(FTransform SpawnTransform, FActorSpawnParameters SpawnInfo, TSubclassOf<AActor> ActorToSpawn );

MyGameMode.cpp

void MyGameMode::SpawnActorFromClass(FTransform SpawnTransform, FActorSpawnParameters SpawnInfo, TSubclassOf<AActor> ActorToSpawn)

{
FTransform SpawnTransform_ =  FTransform;
FTransform MakeTransform_Ret{};
AItemGroup* FinishSpawnClass_{};
FVector Location = SpawnTransform_.GetLocation();
FRotator Rotation = SpawnTransform_.GetRotation();
FVector Scale = SpawnTransform_.GetScale3D();
FActorSpawnParameters SpawnInfo_ = SpawnInfo;

MakeTransform_Ret = UKismetMathLibrary::MakeTransform(FVector(Location), FRotator(Rotation), FVector(Scale));
SpawnInfo_ = UGameplayStatics::BeginDeferredActorSpawnFromClass(this, AItemGroup::StaticClass(), MakeTransform_Ret, ESpawnActorCollisionHandlingMethod::Undefined, ((AActor*)nullptr));
MakeTransform_Ret = UKismetMathLibrary::MakeTransform(FVector(Location), FRotator(Rotation), FVector(Scale));
FinishSpawnClass = CastChecked<AItemGroup>(UGameplayStatics::FinishSpawningActor(SpawnInfo_, MakeTransform_Ret), ECastCheckedType::NullAllowed);
ActorToSpawn = FinishSpawnClass;
}

Why not just

UWorld* World; //Some World

World->SpawnActor<Class>();

Also you should return a ptr to the spawned actor not just void

AActor* MyGameMode::SpawnActorFromClass()

2 Likes

this will work same as this blueprint function? and what about the transforms and other stuff if I want to spawn it dynamically by passing fixed vector transforms from data tables?
just asking to try it on my end if it will work

Yes UWorld::SpawnActor comes with all those parameters as input into the function

Notice how the return pin gives you back a reference to the actor, you will need to modify your function to be AActor* MyGameMode::SpawnActorFromClass() not void.

1 Like

if you right click that function and click goto definition it should take you directly to the kismet version thatโ€™s wrapping UWorld->SpawnActor

1 Like

Thank you Sir for consulting me in this idea, Thank you very much :slight_smile:

1 Like