Created
September 18, 2025 20:22
-
-
Save AldeRoberge/af11fd10e4cb2baead6c18d0628cf309 to your computer and use it in GitHub Desktop.
Scale a unity background to full size in portrait mode, and take about 1/3rd in landscape mode
This file contains hidden or 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 Sirenix.OdinInspector; | |
using UnityEngine; | |
namespace ADG.Scripts.Runtime | |
{ | |
[ExecuteAlways] | |
[RequireComponent(typeof(RectTransform))] | |
public class BackgroundScaler : MonoBehaviour | |
{ | |
[SerializeField, Required, BoxGroup("References")] | |
private RectTransform _rectTransform; | |
private void Reset() | |
{ | |
if (_rectTransform == null) | |
_rectTransform = GetComponent<RectTransform>(); | |
} | |
private void Update() | |
{ | |
UpdateLayout(); | |
} | |
private void UpdateLayout() | |
{ | |
if (Screen.width - 100 > Screen.height) // Landscape | |
{ | |
_rectTransform.anchorMin = new Vector2(0.25f, 0f); // left bound (1/4 from left) | |
_rectTransform.anchorMax = new Vector2(0.75f, 1f); // right bound (1/4 from right) | |
} | |
else // Portrait | |
{ | |
_rectTransform.anchorMin = new Vector2(0f, 0f); | |
_rectTransform.anchorMax = new Vector2(1f, 1f); | |
} | |
_rectTransform.offsetMin = Vector2.zero; | |
_rectTransform.offsetMax = Vector2.zero; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment