Spawning an actor with parameters

How do I pass parameters to a class when spawning it with this line?

camTransition = GetWorld()->SpawnActor(AcameraTransitions::StaticClass(), …stuff…);

I suppose actors are spawned with UWorld::SpawnActor, but how do I access a class constructor? I thought to use a BeginPlay to pass parameters but it looks like this method is called by itself just when actor is spawned.

1 Like

You can’t pass parameters to a class constructor in UE4.

You could create a separate function Initialize() and call it after spawning the actor. There you can then pass all the parameters you need.

So getters and setters are the only way to share parameters? Well, that’s fine. Thank you for an answer.

Could this cause any hiccups or other issues if the parameters also define which mesh to use? Since it is already spawned when the mesh is (re)defined, I am a bit hesitant…

It’s not the best idea, since you can’t add any subobjects after constructor. Or I just messed up.

It would be better to use BeginDeferredActorSpawnFromClass, that way the construction is ran after you initialize it.

FTransform SpawnTransform(Rotation, Origin);
auto MyDeferredActor = Cast<ADeferredActor>(UGameplayStatics::BeginDeferredActorSpawnFromClass(this, DeferredActorClass, SpawnTransform));
if (MyDeferredActor != nullptr)
{
	MyDeferredActor->Init(ShootDir);

	UGameplayStatics::FinishSpawningActor(MyDeferredActor, SpawnTransform);
}
7 Likes

This is the correct answer if you’re using C++ and want to set some values in your blueprint before the constructor and BeginPlay are called.

While there is no explicit way to call Spawn with custom parameters, below is a solution that gets you the same result.

Best answer here. helped me a lot

See Spawn actor with dynamic data - Programming & Scripting - Epic Developer Community Forums

1 Like

I do not think so, I have tried and it is called the constructor before

Correct, a ctor must be called for the object to exist in the first place. Here, we are constructing the object, initializing it with our own data, then spawning it in the world.

How would you solve this problem?

Can you please clarify what problem you are attempting to solve? Or better, please ask it as a separate Question.

I have asked here:
link text

This is the correct answer to this question. Thank you.