Unity中如何设置Horizontal Layout Group内元素等宽不随内容自动缩放
解决方案
1. 调整Day Panel的Horizontal Layout Group配置
- 勾选「Control Child Size」的 Width 选项,允许布局组统一控制子物体宽度
- 勾选「Child Force Expand」的 Width 选项,强制所有子物体平分父容器的可用宽度
如果希望子元素之间有固定间距,可以在「Spacing」参数中设置水平间距值。
2. 为动态生成的Text对象添加Layout Element组件
在你的创建代码中,给每个days[i]添加Layout Element组件,设置flexibleWidth为1,强制所有子元素按相同比例分配宽度,不受Text内容长度影响。修改后代码如下:
days[i].transform.SetParent(GameObject.Find("Day Panel").transform); // 新增:添加Layout Element控制尺寸 LayoutElement layoutElement = days[i].AddComponent<LayoutElement>(); layoutElement.flexibleWidth = 1; // 原有Text配置代码不变 days[i].AddComponent<Text>(); days[i].transform.GetComponent<Text>().font = (Font)Resources.GetBuiltinResource(typeof(Font), "Arial.ttf"); days[i].transform.GetComponent<Text>().fontSize = 25; days[i].transform.GetComponent<Text>().color = Color.black; days[i].transform.GetComponent<Text>().alignment = TextAnchor.UpperCenter; days[i].transform.GetComponent<Text>().text = shownDates[i].Day.ToString(); // 可选:设置文本超出时自动换行,避免内容被截断 days[i].transform.GetComponent<Text>().horizontalOverflow = HorizontalWrapMode.Wrap; days[i].transform.localScale = new Vector3(1, 1, 1); days[i].transform.localPosition = new Vector3(0, 0, 0);
配置完成后所有Text对象会自动平分父容器宽度,不会再被内容长度影响。
内容的提问来源于stack exchange,提问作者Julian
相关产品推荐
相关产品推荐

