How to spawn actors in multiplayer

I’m working on a multiplayer game and it involves spawning a certain Pickup class that the player can then consume when he/she overlaps it.

I tried spawning these Pickups in my GameMode class, GameState class, but they just won’t spawn… How do i manage the spawning and destruction of these Pickups?

You will want to spawn actors on the server. Which class spawns them is mostly irrelevant, though the “reason” for these spawns can determine where they should be implemented. Without context on what kind of pickups are spawning, how often, and where they spawn I am limited in the help I can provide, but I will be happy to give you a generic example.

Assume you want to spawn a pickup every 30 seconds. You can (and should) do this in GameMode since it is a global event that changes depending on what type of game is being played, and the spawn event isn’t attached to any trigger or stimuli outside of time. Assuming you have a custom GameMode class you can do the following:

// MyGameMode.h
#pragma once
#include MyGameMode.generated.h

class AMyGameMode : public AGameMode
{
   GENERATED_BODY()

public:

   void BeginPlay() override;

protected:

   void SpawnPickup();

private:

   FTimerHandle TimerHandle_SpawnPickup;
}

And your cpp file…

// MyGameMode.cpp
#include "MyProject.h"
#include "MyGameMode.h"
#include "MyPickupClass.h"

void AMyGameMode::BeginPlay()
{
   Super::BeginPlay();
   GetWorld()->GetTimerManager().SetTimer(TimerHandle_SpawnPickup, this, &AMyGameMode::SpawnPickup, 30.f /* You should scale this with the global time dilation */, true, 45.f /* Spawn the first pickup after 45 seconds, also scale with global time dilation */);
}

void AMyGameMode::SpawnPickup()
{
    AMyPickupClass = SpawnActor<AMyPickupClass>(AMyPickupClass::StaticClass(), SomeLocation, SomeRotation);
   AMyPickupClass->DoWhateverSetupMethodsYouNeed;
}

Now, it is important that you set your actor to replicate. You can view a nice overview of replication here.

If you want some client event to trigger a spawn you would need to use UFUNCTION(Server, Reliable, WithValidation) and do the same SpawnPickup call wherever else.

This will cause your pickup to be spawned on the server but replicate to clients. This way when a client walks over a pickup it can do what it needs to due to the fact that both the player character and pickup live on the server (meaning you don’t need to worry about client->server pickup messages and interactions).

If you have a more specific question I would be happy to answer.

Thanks for this it was really helpful :wink: issue solved!