Skip to content

Instantly share code, notes, and snippets.

@joonjoonjoon
Created December 7, 2023 10:30
Show Gist options
  • Save joonjoonjoon/0cdfd128e65182fe159440da9b6e289f to your computer and use it in GitHub Desktop.
Save joonjoonjoon/0cdfd128e65182fe159440da9b6e289f to your computer and use it in GitHub Desktop.
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
using TastyTools;
using UnityEngine;
using UnityEngine.UI;
public class ResponsiveCanvasHelper : MonoBehaviour
{
public static bool _DEBUG = false;
public RectTransform mainContainer;
Vector2 resolution;
float sixteenByNine = 16f / 9f;
CanvasScaler scaler;
void OnEnable()
{
StartCoroutine(CheckResolution());
}
IEnumerator CheckResolution()
{
var checkDelay = new WaitForSecondsRealtime(1);
while (true)
{
if (resolution.x != Screen.width || resolution.y != Screen.height)
{
UpdateResponsiveness();
}
yield return checkDelay;
}
}
void UpdateResponsiveness()
{
if(_DEBUG) Debug.LogWarning("Detected window size change");
resolution.x = Screen.width;
resolution.y = Screen.height;
if (scaler == null) scaler = GetComponent<CanvasScaler>();
// check if 16:9 or wider
var diff = (resolution.x / resolution.y) - sixteenByNine;
if (Mathf.Abs(diff) < 0.001f || diff > 0 ) // wider
{
// assume 16:9 or wider
if(_DEBUG) Debug.Log("We're wide!");
scaler.matchWidthOrHeight = 1;
mainContainer.sizeDelta = scaler.referenceResolution;
mainContainer.anchorMax = Vector2.one * 0.5f; // detach
mainContainer.anchorMin = mainContainer.anchorMax;
}
else
{
// assume tall
if(_DEBUG) Debug.Log("We're tall!");
scaler.matchWidthOrHeight = 0;
mainContainer.sizeDelta = Vector2.zero;
mainContainer.anchorMax = Vector2.one; // stretch
mainContainer.anchorMin = Vector2.zero;
}
}
[InspectorButton("DebugMe")] public bool _debug;
public void DebugMe()
{
Debug.Log(mainContainer.anchorMax);
Debug.Log(mainContainer.anchorMin);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment