gpt4 book ai didi

c# - 如何删除 Unity3D 中按钮之间的间距?

转载 作者:行者123 更新时间:2023-12-04 02:45:15 25 4
gpt4 key购买 nike

我正在用 Unity 设计的游戏中以编程方式创建按钮。我实例化按钮预制件并将它们作为 Canvas 上 Panel 对象的父级。我已将面板设置为具有具有以下属性的水平布局组:

enter image description here

我已将以下组件添加到按钮预制件中以实现我需要的外观:

enter image description here

完成所有这些之后,我得到的结果是:

enter image description here

因此,我的问题是,如何去除每个按钮之间的间距?这些按钮应该紧挨着彼此(但不重叠)以看起来像一个句子。我有单独按钮的原因是用户需要单击句​​子中正确的 2 个字母字符(在上面的示例中是字母 ar)。我已将属性的间距设置为 0 并选中/取消选中各种选项,但没有成功!

我已经在 Panel 和 Button 对象上取消选中 Child Force Expand 的宽度选项,但句子看起来都塞满了......我如何确保按钮一个接一个地整齐地放置(即不重叠)?

enter image description here

评论相关代码如下:

 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);
}

最佳答案

取消选中 Child Force Expand: Width

来自 the docs :

Child Force Expand: Whether to force the child layout elements to expand to fill additional available space.

检查宽度(resp。高度)将使元素水平填充可用空间(resp。垂直)。


编辑:不要布局组的子级上放置内容大小调整器。更多信息:Making UI elements fit the size of their content .

根据我们的讨论:因此上述链接中描述的步骤仅适用于最新版本的 Unity。如果您坚持使用更成熟的版本,您可以保留 ContentSizeFitter 以获得所需的结果,但要注意的是,如果您更改子元素的大小,布局将不会正如您所期望的那样自动更新。要解决此问题,您可以强制进行部分重新布局,如 Stephan-Bthis thread 中所解释的那样:

The following function LayoutRebuilder.ForceRebuildLayoutImmediate should prove useful. Instead of forcing a rebuild of all the Canvases which can have a significant performance impact, you can call this function on the root (top parent) object in the hierarchy the contains the layout component affecting the object in question.

关于c# - 如何删除 Unity3D 中按钮之间的间距?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57441800/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com