UE4 Tip: Spawn sounds instantly for client, but network replicated for everyone else.

Posted on September 14, 2019 by the_hack

 

One of the hardest things I needed to learn in Unreal Engine was how to have a connected client instigate an event, and have it replicate for everyone via a RPS, but also happen instantly for themselves, without also replicating back to themselves along with all other clients.

Let’s say a client needs to instigate a sound, such as a jump sound. Let’s say you are working inside the character blueprint (because that’s the one that consumes input such as ‘jump.’

You want that sound to be audiable to all connected clients. This means the client needs to ask the server to tell the clients to play the sound. The standard, easy and much recommended way is to do this:

 

 

But, that means that the jumping client won’t hear jump instantly (unless they are the server) . Because you want instant feedback for the player who jumps, you can’t wait for those instructions to do the rounds. You want to send off the instructions, but also play the sound for yourself only.

That looks like this:

The key is “is locally controlled.” This allows you to control what happens for the local controller of the character, and what happens for others.

How do you test this? Launch a play in editor session with 2 players in new windows.

 

 

Test the soloaudio on the client and server, one after the other to ensure the sound is only playing once, as desired. Use the Net PktLag console command on the client to introduce some time between the action and when the RPC arrives, so you can hear the difference.

Now you have a jump sound that happens only once, and instantly for the locally controlled character, whether that is a client or server player, and as early as possible for everyone else!

Chances are though, that you will want to do this more than once. So let’s create a reusable custom event. In this case, the controller input triggers a client-only event, which passes the sound through to the complete function. In this case, you need to have separate nodes for playing the sound as the sound asset is referenced earlier down the chain. Otherwise, it’s the same.

You can pass through other nodes from the spawn sound node through to the original event. Tip – drag from a node back into a custom event to create an input on that event.

As you may have guessed this can be re-purposed for things like emitters. I use a similar system for many different character-originating gameplay events, including launching the character for non-default things like wall jumps and dodges.

shock and rockets discord