How to attach a particle system to a spawned actor through code?

I’m trying to create a blueprint that will let me spawn an actor and a particle emitter at a location with the option of having the emitter attached to the actor. So far I can’t nail down how exactly to use SpawnEmitterAttached in this context with an actor being spawned by the same function. Also to note, the actor I’m trying to spawn has no other component beyond its static mesh.

.h

#include "CoreMinimal.h"
#include "Kismet/BlueprintFunctionLibrary.h"
#include "TechTestLibrary.generated.h"


UCLASS()
class TECHTEST2_API UTechTestLibrary : public UBlueprintFunctionLibrary
{
	GENERATED_BODY()
	
		UFUNCTION(BlueprintCallable, meta = (WorldContext = "RefObj"))
		static void TestSpawn(
			TSubclassOf<AActor> Actor,
			UParticleSystem* Emitter,
			FTransform Transform,	
			int Amount,
			bool Attached,
			ESpawnActorCollisionHandlingMethod SpawnCollisionHandlingOverride,
			UObject* RefObj			
		);
};

.cpp

void UTechTestLibrary::TestSpawn(
	TSubclassOf<AActor> Actor,
	UParticleSystem* Emitter,
	FTransform Transform,
	int Amount,
	bool Attached,
	ESpawnActorCollisionHandlingMethod SpawnCollisionHandlingOverride,
	UObject* RefObj	
)
{
	UWorld* TechTest = GEngine->GetWorldFromContextObject(RefObj);
			   	 
	for (int i = 0; i < Amount; i++)
	{
		AActor* TestActor = TechTest->SpawnActor<AActor>(Actor, Transform);

		if (Attached) 
		{
			UGameplayStatics::SpawnEmitterAttached(Emitter, TestActor, NAME_None,
				Transform, EAttachLocation::SnapToTarget, false);

		}		
	}

	if (!Attached) 
	{
		UGameplayStatics::SpawnEmitterAtLocation(TechTest, Emitter, Transform, true);
	}			
	
}

First of all, the function goes as follows:

static UParticleSystemComponent * SpawnEmitterAttached
(
    class UParticleSystem * EmitterTemplate,
    class USceneComponent * AttachToComponent,
    FName AttachPointName,
    FVector Location,
    FRotator Rotation,
    FVector Scale,
    EAttachLocation::Type LocationType,
    bool bAutoDestroy,
    EPSCPoolMethod PoolingMethod
)

If you’re using this function, use it as follows:

    if (TestActor && YourTemplate && (YourScale.Size() != 0))
    {
     UGameplayStatics::SpawnEmitterAttached(YourTemplate, TestActor->GetRootComponent(), NAME_None, YourLocation, YourRotation, YourScale, EAttachLocation::SnapToTarget, false, EPSCPoolMethod::AutoRelease
    }

That should work :slight_smile:

This worked perfectly thanks :slight_smile: