VerticalLayoutGroup是Unity UGUI中的一種佈局元件,用於在垂直方向上自動排列子物件。它可以根據子物件的大小和佈局設定,自動調整子物件的位置和大小,實現垂直佈局效果。
VerticalLayoutGroup元件通過以下步驟實現垂直佈局:
using UnityEngine;
using UnityEngine.UI;
public class VerticalLayoutExample : MonoBehaviour
{
public VerticalLayoutGroup verticalLayoutGroup;
private void Start()
{
verticalLayoutGroup.spacing = 10f;
verticalLayoutGroup.childForceExpandWidth = false;
verticalLayoutGroup.childForceExpandHeight = false;
verticalLayoutGroup.childControlHeight = true;
verticalLayoutGroup.childAlignment = TextAnchor.UpperCenter;
}
}
操作步驟:
using UnityEngine;
using UnityEngine.UI;
public class AddChildExample : MonoBehaviour
{
public VerticalLayoutGroup verticalLayoutGroup;
public GameObject childPrefab;
private void Start()
{
for (int i = 0; i < 5; i++)
{
GameObject child = Instantiate(childPrefab, verticalLayoutGroup.transform);
child.GetComponentInChildren<Text>().text = "Child " + (i + 1);
}
}
}
操作步驟:
using UnityEngine;
using UnityEngine.UI;
public class RemoveChildExample : MonoBehaviour
{
public VerticalLayoutGroup verticalLayoutGroup;
private void Start()
{
for (int i = 0; i < verticalLayoutGroup.transform.childCount; i++)
{
Destroy(verticalLayoutGroup.transform.GetChild(i).gameObject);
}
}
}
操作步驟:
using UnityEngine;
using UnityEngine.UI;
public class ResizeChildExample : MonoBehaviour
{
public VerticalLayoutGroup verticalLayoutGroup;
private void Start()
{
for (int i = 0; i < verticalLayoutGroup.transform.childCount; i++)
{
RectTransform childRectTransform = verticalLayoutGroup.transform.GetChild(i).GetComponent<RectTransform>();
childRectTransform.sizeDelta = new Vector2(childRectTransform.sizeDelta.x, 100f);
}
}
}
操作步驟:
using UnityEngine;
using UnityEngine.UI;
public class AlignChildExample : MonoBehaviour
{
public VerticalLayoutGroup verticalLayoutGroup;
private void Start()
{
verticalLayoutGroup.childAlignment = TextAnchor.MiddleCenter;
}
}
操作步驟: