LoginSignup
27
25

More than 3 years have passed since last update.

Unity WebGL ブラウザの大きさに合わせる

Last updated at Posted at 2017-04-18

Unity側だけの知識ではハマる!

ブラウザの大きさに応じて画面をリサイズしていくような処理は、
Unity側で出来ないことはないけど手軽ではないという結論に至った。
htmlやjavascript、cssの知識を活用して今回はこの問題を解決する。

1.Unity側の作業

Unity側の作業はロゴを消すぐらい。

File>Build Settings>Player Settings
Resolution and Presentation
WebGL TemplateをDefault→Minimalへ変更

スクリーンショット 2017-04-18 20.03.18.png

念の為下記も設定しておくといいかも。

  • File>Build Settings>Player Settings
  • Resolution and Presentation
  • Default Screen Width {Canvas Scaler Refernce resolution xの値}
  • Default Screen Height {Canvas Scaler Refernce resolution yの値}

※ここの値は書き出されたindex.htmlのcanvasのwidthとheightに反映されるだけなので、不要っちゃ不要。

2.windowsResize.jsの作成(js久しぶりすぎて、ほとんど忘れてた。。)

var container;
var canvas;
var timer = 0;

//初期化
function init() {
    canvas = document.getElementById('canvas');
    container = document.createElement('div');
    container.style.width = window.innerWidth + 'px';
    container.style.height = window.innerHeight + 'px';
    container.style.overflow = 'hidden';
    container.appendChild(canvas);
    document.body.appendChild(container);
    document.body.style.margin = '0px'
}

//サイズ変更処理
function resize() {
    container.style.width = window.innerWidth + 'px';
    container.style.height = window.innerHeight + 'px';
    canvas.width = window.innerWidth * window.devicePixelRatio;
    canvas.height = window.innerHeight * window.devicePixelRatio;
}

window.onload = function () {
    init();
    resize();
};

//ブラウザの大きさが変わった時に行う処理
(function () {
    var timer = 0;
    window.onresize = function () {
        if (timer > 0) {
            clearTimeout(timer);
        }
        timer = setTimeout(function () {
            resize();
        }, 200);
    };
}());

3.windowsResize.jsの配置

書き出したindex.htmlと同階層にwindowsResize.jsを置く。
スクリーンショット 2017-04-18 20.24.12.png

4.書き出し後のindex.htmlの修正

・index.htmlに1行追加

<script type="text/javascript" src="windowResize.js"></script>

※head内だったらどこでもOK。タグの間に書くとか斜め上のことはやらないでください。

5.最後に

後はUnity側のUI配置を画面サイズが変わっても崩れないように配置すればOK(これが一番大変そう)

27
25
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
27
25