Created
February 14, 2023 14:48
-
-
Save ina-amagami/71021d1c3f806bea86b843e853d7e8d5 to your computer and use it in GitHub Desktop.
モバイル表示でもPCのワイド表示でもちょうど良い感じに表示するためのCanvasScaler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using UnityEngine.UI; | |
/// <summary> | |
/// PC/モバイル両方にレスポンシブ対応するためのCanvasScaler | |
/// </summary> | |
public class ResponsiveCanvasScaler : CanvasScaler | |
{ | |
private float _defaultMatchWidthOrHeight; | |
private int _cachedWidth; | |
protected override void Awake() | |
{ | |
_defaultMatchWidthOrHeight = m_MatchWidthOrHeight; | |
} | |
private void Update() | |
{ | |
if (!Application.isPlaying) | |
{ | |
return; | |
} | |
if (_cachedWidth == Screen.width) | |
{ | |
return; | |
} | |
_cachedWidth = Screen.width; | |
var matchWidth = Mathf.Lerp(m_ReferenceResolution.x, m_ReferenceResolution.y, _defaultMatchWidthOrHeight); | |
if (_cachedWidth > matchWidth) | |
{ | |
uiScaleMode = _cachedWidth > m_ReferenceResolution.x ? | |
ScaleMode.ConstantPixelSize : ScaleMode.ScaleWithScreenSize; | |
if (uiScaleMode == ScaleMode.ScaleWithScreenSize) | |
{ | |
m_MatchWidthOrHeight = | |
Mathf.InverseLerp(m_ReferenceResolution.x, matchWidth, _cachedWidth) * _defaultMatchWidthOrHeight; | |
} | |
} | |
else | |
{ | |
uiScaleMode = ScaleMode.ScaleWithScreenSize; | |
m_MatchWidthOrHeight = _defaultMatchWidthOrHeight; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment