Skip to content

Instantly share code, notes, and snippets.

@t5ujiri
Last active June 14, 2021 10:45
Show Gist options
  • Save t5ujiri/b9cf812048ae902a826ca94e032ba4ab to your computer and use it in GitHub Desktop.
Save t5ujiri/b9cf812048ae902a826ca94e032ba4ab to your computer and use it in GitHub Desktop.
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