How can I determine which connection spawned a pawn possessed by an AI controller?

I need to determine which connection (which client and/or server) spawned a certain actor. The problem is that this actor is automatically possessed by an AI controller when it spawns, which overrides the “owner” spawn parameter, and prevents me from using GetOwner() to determine the owning connection.

Is there a way to get the owning connection some other way? Also, once I get the owning player, how can I use that information to say “do this if you’re the owning player, do this if you’re not”?

The simplest solution we have found is to add a pointer to the owning player and assigning the owning player when the server spawns any actor.

UClass()
class SomeActorClass : public AActor
{

UPROPERTY(Replicated)
TWeakObjectPtr OwningPlayer = nullptr;


}

When the server spawns an actor, use deferred spawning so that you can set the owning parameters before the actor is finished spawning. Below is the actual spawning code I use for multiplayer games.

void ASW_RTSGameModeBase::SpawnUnit(TSubclassOf<ASW_Unit> UnitClass, FVector Location, FQuat Orientation, FVector Scale, ASW_PlayerController* OwningPlayer)
{
	if ((HasAuthority()) && (OwningPlayer!=nullptr))
	{
		UWorld* World = GetWorld();
		if (World != nullptr)
		{
			FTransform SpawnTransform;
			SpawnTransform.SetLocation(Location);
			SpawnTransform.SetRotation(Orientation);
			SpawnTransform.SetScale3D(Scale);

			ASW_Unit* SpawnedUnit = World->SpawnActorDeferred<ASW_Unit>(UnitClass, SpawnTransform, OwningPlayer, OwningPlayer->GetPawn(), ESpawnActorCollisionHandlingMethod::AdjustIfPossibleButAlwaysSpawn);
			if (SpawnedUnit != nullptr)
			{
				SpawnedUnit->SetOwningPlayer(OwningPlayer);
				SpawnedUnit->FinishSpawning(SpawnTransform);
			}
		}
	}
}

Through the OwningPlayer pointer you can easily check for ownership regardless of how the actor is actually controlled.

//If owned by local player, then perform code
if (UGameplayStatics::GetPlayerController(GetWorld(), 0)==OwningPlayer)
{

}

NOTE: We perform spawning only on the server, passing the player controller that is requesting an actor spawn to the server.

3 Likes

Interesting. Thank you for the advice!