I would like to mix interactive WebGL content with plain old html elements on a website. Currently, I’m loading a WebGL build once when the site is first loaded and hide and show it as needed via Javascript and CSS, passing in a string to change what’s supposed to be displayed. I came up with this because I thought creating a new instance each time would mean waiting for the build to load again and again.
But I believe just hiding the WebGL canvas via JS & CSS doesn’t in any way communicate that the player should stop and resume, meaning it still receives input events (using the new Input System clicks and drags are still registered), continues rendering and calling Update() etc.
Is there a recommended way to handle situations like this? e.g.
a) some way to completely halt and resume execution of a Unity WebGL player or
b) do something similar by hand? (I was thinking about disabling/re-enabling all GameObjects and maybe switch settings like the target framerate between 1 and 30 for example, but that feels wrong and cumbersome).
Looking forward to any insights, thank you!
(3 years later…) As of today, it all depends from the HTML canvas element where the Unity instance is created.
When that canvas is completely hidden from view, e.g. with a CSS display: none;, then the Unity engine will stop running. You can verify that by having the Unity app logging to console in some MonoBehaviour:
void Start()
{
StartCoroutine(HeartbeatSteps());
}
IEnumerator HeartbeatSteps()
{
// this will print a message to console repeatedly and
// indefinitely, as long as engine is running.
// It should suspend when web canvas loses focus
var count = 0;
while (true)
{
yield return new WaitForSeconds(2f);
count++;
Debug.Log($"[HeartBeat] Running {count}");
}
}
and having the browser with its developer tool console open side by side with the page. When the canvas is visible, messages will show up in console, otherwise no message is printed.
Just as a side note, the same happens e.g. on a PC when the canvas is visible but the browser window is hidden by another window, ot the browser is minimized.
Not all “ways of hiding” works though. E.g. with CSS there was a property (I think it was visibility: hidden;) that even when applied did not prevent Unity engine from running.