Trying to access pointer from client crashes game?

I have a server function inside of my player pawn, which is called from a widget. The function spawns an actor to which the widget needs a pointer, but RPCs can’t return values. So I tried to pass a pointer to the widget into the server function. Then the server function uses the pointer to access and set the variable that holds the reference to the spawned actor (the actor I’m spawning is a piece for a board game-like RTS):

void AMatch_PlayerPawn::SpawnPiece_Server_Implementation(UClass* ClassToSpawn, FVector PieceSpawnLocation, FRotator PieceSpawnRotation, UPieceDragWidget* PieceDragWidgetRef)
{
/* Define additional spawn parameters. */
FActorSpawnParameters SpawnParams;
SpawnParams.Owner = this;
SpawnParams.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AdjustIfPossibleButAlwaysSpawn;

/* Spawn an actor of the given class and set a reference to it in the drag widget. */
PieceDragWidgetRef->SpawnedPiece = GetWorld()->SpawnActor
(
ClassToSpawn,
&PieceSpawnLocation,
&PieceSpawnRotation,
SpawnParams
); // this is line 75
}

On the server, this all works perfectly, and has the intended result. But when I try to call it on the client, the game crashes with this error:

UE4Editor_Kingdoms_8853!AMatch_PlayerPawn::SpawnPiece_Server_Implementation() [G:\My Drive\Projects\Commercial\Kingdoms\Kingdoms\Source\Kingdoms\Private\Framework\Match\Match_PlayerPawn.cpp:75]
UE4Editor_Kingdoms_8853!AMatch_PlayerPawn::execSpawnPiece_Server() [G:\My Drive\Projects\Commercial\Kingdoms\Kingdoms\Intermediate\Build\Win64\UE4Editor\Inc\Kingdoms\Match_PlayerPawn.gen.cpp:64]

Does anyone know why this crash could be happening?

Thanks in advance!

Edit: Sorry about the code formatting. The forum won’t show tabs or spaces for some reason.

Widget are exclusive to clients. In an RPC function, you can only pass pointers to things that exist both on the server and the client, but widgets don’t exist on the server.

Maybe try making 2 functions: the first from client to server with the spawn request, the other from server to client with the actor pointer.

Or, depending on how you spawn the actor, maybe you can get the reference to it from its begin play function? E.g. you SpawnActorDeferred, set a replicated variable in it pointing to the player/controller that initiated spawning, and make it set a client reference by itself?

1 Like

Aah, that makes sense. How do you recommend I give the actor pointer from the server to the client?