Last active
July 1, 2019 08:45
-
-
Save Estecka/23661e196cf82e52d779aa180f2ac414 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 System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
[ExecuteAlways] | |
[RequireComponent(typeof(RectTransform))] | |
public class SubCanvasScaler : MonoBehaviour { | |
public enum ScalingMode { | |
Stretch, | |
MatchHeight, | |
MatchWidth, | |
} | |
public ScalingMode scalingMode = ScalingMode.Stretch; | |
RectTransform parent => transform.parent as RectTransform; | |
RectTransform rectTransform => transform as RectTransform; | |
Vector2 from, to; | |
#if UNITY_EDITOR | |
void Update(){ | |
if (!Application.isPlaying) | |
LateUpdate(); | |
} | |
#endif | |
void LateUpdate(){ | |
if (from != rectTransform.rect.size || to != parent.rect.size) | |
ForceUpdateLayout(); | |
} | |
public void ForceUpdateLayout(){ | |
rectTransform.pivot = | |
rectTransform.anchorMax = | |
rectTransform.anchorMin = new Vector2(0.5f, 0.5f); | |
rectTransform.anchoredPosition = Vector2.zero; | |
from = rectTransform.rect.size; | |
to = parent.rect.size; | |
Vector3 scale = Vector3.one; | |
switch (this.scalingMode){ | |
default: | |
case ScalingMode.Stretch: | |
scale.x = to.x / from.x; | |
scale.y = to.y / from.y; | |
break; | |
case ScalingMode.MatchHeight: | |
scale.x = | |
scale.y = to.y / from.y; | |
break; | |
case ScalingMode.MatchWidth: | |
scale.y = | |
scale.x = to.x / from.x; | |
break; | |
} | |
rectTransform.localScale = scale; | |
} | |
} |
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
fileFormatVersion: 2 | |
guid: 7a8923493ce94ea40a6f93ed4f89e61a | |
MonoImporter: | |
externalObjects: {} | |
serializedVersion: 2 | |
defaultReferences: [] | |
executionOrder: 0 | |
icon: {fileID: 1430608953724808672, guid: 0000000000000000d000000000000000, type: 0} | |
userData: | |
assetBundleName: | |
assetBundleVariant: |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment