One huge part of the engine was not touched by me long time before. And now after a week digging in, I realized that something is VERY wrong with multiplayer. I will show you how the most trivial task becomes a nightmare when you try to implement it in server-client configuration.
Task: set random color for every character. Setup - listen server and two clients.
If you are beginner you probably just try something like this:
- Generate random color on server.
- Set color to Character which replicates by default.
I imagine that almost every beginner thinks that replication is the magic wand, so all you need is to set replicates on every actor you want to see on clients, but it doesn’t work like this.
And somehow you need to understand this by yourself in hundreds experiments.
In fact you should keep in mind a lot of information to make something working.
First of all this diagram from wonderful eXi’s network compendium:
It describes object existence in every instance. By the way there are 3 actually levels, each on every “PC”. We will name them ServerWorld, World1 and World2. Before I just set colors for characters in ServerWorld.
So as you can see there are actually 9 characters overall. 3 for every world. *But I’m sure you already read somewhere that server controls only movement. *To set the exact color for every character you should:
- Generate random color and **save **it on **server **in object **existed **on every instance. PlayerCharacters (pawns) fit this task. You can also use PlayerStates or GameState.
- Call function on every instance for every character to set the color using saved value from server. Value should be replicated.
Did I promise pain before? Here it is!
It doesn’t work! Lol. You should wait while value replicates to every instance (even if it’s the same computer, sick!). And 0.2 sec delay is not enough! Put 1 sec delay before calling multicast event and finally you could set correct colors on every instance.
Btw, I found the RepNotify pretty easy way to use in this case. You don’t need to think about delays at this point.
Ok. It’s tricky but kinda easy when you work with Character, because it exists ns on every instance. Roughly speaking Player1 can do stuff in World2. But in big projects usually PlayerController is the main class you working with. So if you want to make same task with colors but using PC next list for you:
- You call the server event on PC that will generate random color and save it in gamestate because it exists on every instance and PC doesn’t (you can read variables from PC only on the server).
- You call the multicast event on the gamestate and send your pawn to it. You can only call this event from server!! So Gamestate will call SetColor function for exact pawn in every world.
Or even more often situation:
And all this just because actors don’t replicate their parameters. The end.