htmlcssunity-game-enginescreen-sizeunity-webgl

Prohibit changing the game resolution in Unity WebGL


I have a Unity WebGL game. The browser window can be changed as you like, so the game can be severely deformed. How to make the game always maintain its proportions regardless of the browser resolution?

I think it can be configured only in HTML, so in style.css I wrote

min-width: 100vw; min-height: 100vh;

out of desperation, I have already tried to fit it into all the elements: html, body; canvas; body; #unity-container; #unity-canvas. But browsers don't care about this code. There is no result.


Solution

  • I was able to figure out this problem. We need to write this code in index.html

    <script>
    function resizeGame() {
          var gameContainer = document.getElementById("unity-container");
          var widthToHeight = 16 / 9;
          var newWidth = window.innerWidth;
          var newHeight = window.innerHeight;
          var newWidthToHeight = newWidth / newHeight;
    
          if (newWidthToHeight > widthToHeight) {
              newWidth = newHeight * widthToHeight;
            } else {
              newHeight = newWidth / widthToHeight;
          }
    
          gameContainer.style.width = newWidth + 'px';
          gameContainer.style.height = newHeight + 'px';
        }
    
        window.addEventListener('resize', resizeGame, false);
        resizeGame();
    </script>