Search code examples
unity-game-engineparent-childscale

Unity: Fit size of parent to size of childs


I have an empty in a Canvas that has multiple objects as children. More children are added to the parent as the game progresses. I want the parent to fit the size to its children.

I already read a lot about this topic, but every time I came across the ContentSizeFitter, which unfortunately does not work for me, because it needs a layout group, which I do not have, because the children do not have an order and are wildly placed.

I am using Unity 2018.3.4f1 Personal.

Not sized parent:

Example

Sized parent (Red: New, Green: Old):

Example 2

Structure:

Canvas
 |- Empty
     |- Child 1
     |- Child 2
     |- Child X

Solution

  • I have written a small piece of code that does its job, or does it the way I want and it is enough for me:

    using UnityEngine;
    
    public class SizeFitter : MonoBehaviour {
        public void CheckForChanges() {
            RectTransform children = transform.GetComponentInChildren<RectTransform>();
    
            float min_x, max_x, min_y, max_y;
            min_x = max_x = transform.localPosition.x;
            min_y = max_y = transform.localPosition.y;
    
            foreach (RectTransform child in children) {
                Vector2 scale = child.sizeDelta;
                float temp_min_x, temp_max_x, temp_min_y, temp_max_y;
    
                temp_min_x = child.localPosition.x - (scale.x / 2);
                temp_max_x = child.localPosition.x + (scale.x / 2);
                temp_min_y = child.localPosition.y - (scale.y / 2);
                temp_max_y = child.localPosition.y + (scale.y / 2);
    
                if (temp_min_x < min_x)
                    min_x = temp_min_x;
                if (temp_max_x > max_x)
                    max_x = temp_max_x;
    
                if (temp_min_y < min_y)
                    min_y = temp_min_y;
                if (temp_max_y > max_y)
                    max_y = temp_max_y;
            }
    
            GetComponent<RectTransform>().sizeDelta = new Vector2(max_x - min_x, max_y - min_y);
        }
    }