UIContentFitter.cs 883 B

12345678910111213141516171819202122232425262728293031323334
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. public class UIContentFitter : MonoBehaviour
  6. {
  7. // Start is called before the first frame update
  8. void Start()
  9. {
  10. Fit();
  11. }
  12. // Update is called once per frame
  13. void Update()
  14. {
  15. }
  16. public void Fit()
  17. {
  18. HorizontalLayoutGroup hg = GetComponent<HorizontalLayoutGroup>();
  19. int childCount = transform.childCount - 1;
  20. float childWidth = transform.GetChild(0).GetComponent<RectTransform>().rect.width;
  21. float width = hg.spacing * childCount +
  22. childCount * childWidth +
  23. hg.padding.left +
  24. childWidth;
  25. Vector2 size = GetComponent<RectTransform>().sizeDelta;
  26. GetComponent<RectTransform>().sizeDelta = new Vector2(width, size.y);
  27. }
  28. }