Last active
June 14, 2021 10:45
-
-
Save t5ujiri/b9cf812048ae902a826ca94e032ba4ab to your computer and use it in GitHub Desktop.
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; | |
[RequireComponent(typeof(RectTransform))] | |
[ExecuteAlways] | |
[DefaultExecutionOrder(-100)] | |
public class SafeArea : MonoBehaviour | |
{ | |
private DeviceOrientation _postOrientation; | |
private RectTransform _rect; | |
[SerializeField] private bool comfortXMax = true; | |
[SerializeField] private bool comfortXMin = true; | |
[SerializeField] private bool comfortYMax = true; | |
[SerializeField] private bool comfortYMin = true; | |
private void Awake() | |
{ | |
_rect = GetComponent<RectTransform>(); | |
} | |
private void Start() | |
{ | |
AdjustView(); | |
} | |
private void Update() | |
{ | |
AdjustView(); | |
} | |
private void AdjustView() | |
{ | |
if (Input.deviceOrientation != DeviceOrientation.Unknown && _postOrientation == Input.deviceOrientation) | |
return; | |
_postOrientation = Input.deviceOrientation; | |
var area = Screen.safeArea; | |
var resolution = Screen.currentResolution; | |
_rect.sizeDelta = Vector2.zero; | |
var xMax = comfortXMax ? area.xMax / resolution.width : 1; | |
var yMax = comfortYMax ? area.yMax / resolution.height : 1; | |
var xMin = comfortXMin ? area.xMin / resolution.width : 0; | |
var yMin = comfortYMin ? area.yMin / resolution.height : 0; | |
_rect.anchorMax = new Vector2(xMax, yMax); | |
_rect.anchorMin = new Vector2(xMin, yMin); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment