0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Unity】画面比率を維持するWindowsアプリを作る方法

Posted at

eyecatch_2110KeepAspectRatingForUnity-fs8.png

※ 本稿は Tech Inside Drecom に掲載された記事、「【Unity】画面比率を維持するWindowsアプリを作る方法」の Qiita 出張版です。


はじめに

こんにちは、Unityエンジニアをやっている竹内です。
今回は、「Windows版のアプリ制作時に画面比率を維持したままウィンドウサイズを可変に対応する」という実装したことについてまとめました。

達成したい項目

任意のサイズにウィンドウサイズをリサイズできるようにしたい
アスペクト比は維持したままリサイズさせたい
最小、最大ウィンドウサイズを指定したい
縦長のウィンドウなどがあるので最大化ボタンは押せないようにしたい
上記全ての項目をスプラッシュスクリーン中も行いたい

サンプルプロジェクトのURL:
https://github.com/oTAMAKOo/Example-StandAloneWin 

1.jpg

任意のサイズにウィンドウサイズをリサイズできるようにしたい

この問題の対応は簡単です
Edit > Project Settings > Player > Resolution and Presentation
から下記の設定画面を開き次の設定に変更します。

  • 「Fullscreen Mode」を「Windowed」にする
  • 「Resizable Window」にチェックを入れる

2.png

アスペクト比維持問題

この問題を解決する為には下記の対応を行います ウィンドウサイズを監視して一定間隔で Screen.SetResolutionでウィンドウサイズを強制的に指定した比率にリサイズする この時にGameObjectのUpdate関数などでリサイズしようとするとスプラッシュ表示中はユーザーが好きな比率でサイズ変更できてしまうという問題が発生します

この問題を解決する為に下記の実装を行います。

  • RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded) で監視を開始
  • Task.Runで非同期で監視を行う
  • 定期的に処理したいのでwhile(true)でループ
  • await Task.Delay(10);などで一定時間毎に処理を実行

サンプルプロジェクトでは下記コードで実装をしています
https://github.com/oTAMAKOo/Example-StandAloneWin/blob/315991c362ad52fd226c5d41c376ca28b37e2eae/Example-StandAloneWin/Assets/Scripts/Modules/StandAloneWindows/Handlers/AspectRatioHandler.cs#L250

最小、最大ウィンドウサイズを指定したい

この問題は前の項で定期チェックを行う際に最小、最大サイズにリサイズ時のサイズを制限する事で実現する事ができます。

サンプルプロジェクトでは下記コードで実装をしています
https://github.com/oTAMAKOo/Example-StandAloneWin/blob/315991c362ad52fd226c5d41c376ca28b37e2eae/Example-StandAloneWin/Assets/Scripts/Modules/StandAloneWindows/Handlers/AspectRatioHandler.cs#L199

縦長のウィンドウなどがあるので最大化ボタンは押せないようにしたい

3.png

この問題を解決する為に下記の実装を行います。

  • RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSplashScreen)でウィンドウスタイルを変更する

スプラッシュの前にウィンドウスタイルを変更する必要があるのでBeforeSplashScreen のタイミングでWin32 APIを呼び出してウィンドウスタイルを変更します。

サンプルプロジェクトでは下記コードで実装をしています
https://github.com/oTAMAKOo/Example-StandAloneWin/blob/master/Example-StandAloneWin/Assets/Scripts/Modules/StandAloneWindows/Handlers/WindowStyleHandler.cs

まとめ

Windows版アプリ作成時に画面比率系の問題を解決したことについてまとめました 。
結果として画面サイズを変更できるようにしつつ比率を綺麗に維持できるようになりました。
最後まで読んでくださりありがとうございます。


Tech Inside Drecom の最新の情報は Facebook や Twitter からお届けしています、フォローよろしくおねがいします!

※ その他の Tech Inside Drecom の記事は、コチラからお探しいただけます!

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?