CategoriesC++Unreal Engine

Syncing random (animation) between clients.

In multiplayer projects there are cases when you need sync random (not only for animations) between clients; The first and the obvious idea is to use Random Stream and seed; But there’s a question how to sync the seed between clients and also make it unique for all actors that will be in use of it. The solution is simple and elegant.

Firstly we need to uniquly identify Actors between the clients and server.

C++
int32 UPB_BlueprintFunctionLibrary::GetNetGIUD(UObject* WorldContextObject, AActor * InActor)
{
	UWorld* World = WorldContextObject->GetWorld();
	
	if(!World->IsGameWorld())
	{
		return 0;
	}
	
	FNetworkGUID NetId = World->GetNetDriver()->GuidCache->GetOrAssignNetGUID(InActor);
	int32 Seed = NetId.ObjectId;
	int32 Default = FNetworkGUID::GetDefault().ObjectId;
	
	// can't find NetGUID in NetGUIDLookup, default was assigned
	ensureAlways(Seed != Default);
	
	return Seed;
}