Hello everyone.
I am developing multiplayer Unity Webgl game.
If players change tab, update is not working well and the game status is not same on both side.
I’d like to synchronize the game even if one player is on the background mode.
Thanks and regards.
I don’t think this can be achieved with the modern browsers. For example MS Edge has feature called “sleeping tabs”.
and together with the “Efficiency mode”:
I tried it and my WebGL build was paused by browser after 5 minutes, but as the description says it can be even less (probably on devices running on battery, or some low end laptops). This features are on by default, so the only easy way around it is if your game plays some audio, but if the user mutes the tab or the music/sounds in game settings then the entire tab with your game will be paused.
I think you should just sync the game, when the user returns back to the tab.
Exactly.
You’ll need either a way of fast-forwarding the game to when focus resumes, or have an authoring host server which does the main game simulation and sends updates to players.
If that server is part of a client (and not a real server), you’ll need dynamic swapping of the host in case that one goes to sleep.
Thank you for your reply.
Can you explain how to turn on Efficiency mode on unity?
You can’t. This is not Unity feature. It is a browser feature, Microsoft Edge web browser in this example. Since it’s built on Chromium, it is safe to assume that all similar web browsers have similar core features (Chrome, Opera, etc…).
Under Project Settings → Player → Resolution and Presentation there is an option “Run In Background”:

Try enabling that. What it does is it makes Unity to update the game in the background using browser’s setTimeout() timing logic, instead of using requestAnimationFrame() API.
requestAnimationFrame() has that behavior that you are describing that updates will not occur in the background. This is an intentional design from the browser to save performance. So the Run In Background option is provided by Unity to let users opt in into a setTimeout() loop, which does work in the background.
However, do note that starting from Chrome 88 in ~January 2021 browser vendors have also begun to aggressively throttle such setTimeout() events in background tabs, so the Run In Background option might not be waterproof. See Limitación intensa de los cronómetros de JS en cadena a partir de Chrome 88 | Blog | Chrome for Developers . That is a bit unfortunate.
If you think your use case should be supported by web browsers, but their current choice to throttle is preventing that, looks like there is a ticket at WHATWG standards body that would relate to discuss use cases under this area: Throttling and clamping of setTimeout and setInterval · Issue #7941 · whatwg/html · GitHub (or opening a new one might be an option as well)
Thank you for your help. Please let me know if you have good solutions.