I declare variables directly in .cpp file to make the “DoOnce” function.
I found that this global variable seems to be Replicated. When I modify it on server by one client, the values of other clients also changed. When I declare this variable in .h file, this problem is solved.
Does anyone know why?
If I had to guess. You are seeing this work when testing multiplayer in the editor but this behavior is not happening in builds.
When testing in multiplayer there may be new windows that pop up, but those windows are actually all part of the same application (the unreal editor). Since each game is part of the same application they all share the same global memory, meaning all global variables are shared. You can imagine that your game is just one big class and the editor is just creating a new instance of your game for each additional client. The global variables are all shared across the unreal editor and since your games are running as part of the editor they all modify and read the same variable.
Builds are run as independent applications though so the global memory is not going to be available across each player’s game.
Variables on actors, components and such are not global so changing a variable on an actor in one game doesn’t propagate to the other automatically. This is true both in editor and in builds. The replication flag for variables tell Unreal to keep an eye out for changes to a variable and to send an update to the other players games of the new value.