Download

Useful C++ Functions

I have a few so figured I’d post them.

Spawn Actor with parameters:

I set this generic one in my top level actor class, and then override in each subactor class when I need extra parameters.

Top level:



template <typename T>
static T* SelfSpawn(UClass* ClassName, UWorld* World, AActor* OwnerParam, FTransform SpawnTransform = FTransform())
{
	if(!World)
	{
		return nullptr;
	}

	T* ThisActor = World->SpawnActorDeferred<T>(ClassName, SpawnTransform, OwnerParam);

	AActor* NewActor = UGameplayStatics::FinishSpawningActor(ThisActor, ThisActor->GetTransform());

	return Cast<T>(NewActor);
}


Subactor level example:



ASomeClass* ASomeClass::SelfSpawn(UWorld* World, AActor* OwnerParam, FString Path, FTransform SpawnTransform, float InputSpeed, float InputAccel, FVector Dir, bool Bounce, uint16 BounceCount, float TimeLimit, float CurveAngle, USceneComponent* LockOnComponent, float LockOnTime)
{
	if(!World)
	{
		return nullptr;
	}

	FActorSpawnParameters Params = FActorSpawnParameters();
	Params.Owner = OwnerParam;
	ASomeClass* ThisActor = World->SpawnActorDeferred<ASomeClass>(ASomeClass::StaticClass(), SpawnTransform, OwnerParam);
	ThisActor->FlipbookComponent->SetFlipbook(Cast<UPaperFlipbook>(StaticLoadObject(UPaperFlipbook::StaticClass(), NULL, *Path)));

	ThisActor->Speed = InputSpeed;
	ThisActor->Accel = InputAccel;
	ThisActor->MoveDir = Dir;
	ThisActor->Bounce = Bounce;
	ThisActor->BounceCount = BounceCount;
	ThisActor->TimeLimit = TimeLimit;
	ThisActor->TurningAngle = CurveAngle;
	ThisActor->LockedOnComponent = LockOnComponent;
	ThisActor->LockOnTime = LockOnTime;

	AActor* NewActor = UGameplayStatics::FinishSpawningActor(ThisActor, ThisActor->GetTransform());

	ASomeClass* ThisNewActor = Cast<ASomeClass>(NewActor);

	return ThisNewActor;
}


Then you call like either:



ASomeClass::SelfSpawn<ASomeClass>(ASomeClass::StaticClass(), World, this, FTransform());


Or for overridden:



ASomeOtherClass::SelfSpawn(World, this, FTransform() /*Other parameters*/);


This one converts a DataTable to an array of the specific struct type for the DataTable so you can do array functions on it(why can’t you use the json functions outside the editor anyway?):



template <typename T>
static FORCEINLINE TArray<T> DataTableToArray(UDataTable* Table)
{
	const FString ContextString(TEXT("GENERAL"));
	TArray<FName> Names = Table->GetRowNames();
	TArray<T> Output;

	for(int i = 0; i < Names.Num(); i++)
	{
		T* Row = Table->FindRow<T>(Names*, ContextString);
		Output.Add(*Row);
	}

	return Output;
}


Nice thanks!