我正在Unity中设计的游戏中以编程方式创建按钮。我实例化按钮预制件并将它们作为子对象放在画布上的面板对象中。我已经设置了该面板的水平布局组,并具有以下属性:
我已经将以下组件添加到按钮预制件中,以实现我需要的外观:
在完成所有这些步骤后,我得到了以下结果: 因此,我的问题是,我如何删除每个按钮之间的间距?按钮应该紧贴在一起(但不重叠),看起来像一个句子。我之所以有单独的按钮,是为了让用户在句子中点击正确的两个字母字符(在上面的示例中是字母ar
)。我已将属性上的间距设置为0
并检查/取消选中各种选项,但没有运气! 我已取消选中面板和按钮对象的Child Force Expand的宽度选项,但句子看起来很挤....我该如何确保按钮整齐地排列在彼此后面(即不重叠)?
以下是与下方评论相关的代码:
for (int i = 0; i < letterArray.Length; i++)
{
button = (GameObject)Instantiate(buttonPrefab);
button.transform.SetParent(buttonPanel.transform, false);
button.GetComponentInChildren<Text>().text = letterArray[i];
FitButtonWidthToText();
}
}
public void FitButtonWidthToText()
{
int widthOfTheText = 0;
CharacterInfo characterInfo;
foreach (char c in button.GetComponentInChildren<Text>().text)
{
button.GetComponentInChildren<Text>().font.GetCharacterInfo(c, out characterInfo, button.GetComponentInChildren<Text>().fontSize);
widthOfTheText += characterInfo.advance;
}
buttonTransform.sizeDelta = new Vector2(widthOfTheText, buttonTransform.sizeDelta.y);
}
LayoutRebuilder.ForceRebuildLayoutImmediate(button.transform);
我不确定作为函数参数传递什么...是按钮rect transform,因为它是文本组件的父级吗? - Lloyd