using System.Linq;
using UnityEngine;
public class ChildrenToFitScreen : MonoBehaviour
{
public UIWidget ObjectOfReference;
public uint EdgeDistance;
UIRoot m_root;
float m_ratio;
bool isDone;
void Awake()
{
isDone = false;
}
void Start()
{
m_root = FindObjectOfType<UIRoot>();
var zoomRatio = (float)m_root.activeHeight / Screen.height;
var ratioX = Screen.width * zoomRatio / (ObjectOfReference.width + EdgeDistance);
var ratioY = Screen.height * zoomRatio / (ObjectOfReference.height + EdgeDistance);
m_ratio = Mathf.Min(ratioX, ratioY);
}
void Update()
{
if (isDone) return;
resizeChildren(transform, m_ratio);
}
void resizeChildren(Component parent, float scale)
{
var scaleAxis = new Vector3(scale, scale, 0);
var list = parent.GetComponentsInChildren<Transform>();
foreach (var children in list.Where(children => !children.localScale.Equals(scaleAxis)).Where(children => children.parent.GetInstanceID() == parent.GetInstanceID()))
{
if (children.gameObject.GetComponent<UISpriteAnimation>())
{
var sprite = children.gameObject.GetComponent<UISprite>();
var animatedWidget = children.gameObject.AddMissingComponent<AnimatedWidget>();
animatedWidget.width = sprite.width * scaleAxis.x;
animatedWidget.height = sprite.height * scaleAxis.y;
}
else
{
children.localScale = scaleAxis;
var x = children.localPosition.x;
var y = children.localPosition.y;
children.localPosition = new Vector3(x * scale, y * scale, 0);
}
}
isDone = true;
}
}