我想单击一个按钮并更改其文本的颜色和消息属性。
我得到了更改其颜色的按钮,但是我需要更改其文本的颜色之一。
private void TurnGreen(Button button)
{
ColorBlock colors = button.colors;
colors.normalColor = Color.green;
button.colors = colors;
}
上面的代码更改了我喜欢的按钮颜色,但是我宁愿更改按钮的文本。但是请注意,我的按钮有两个text-childs。我要更改的文本的名称为“矿石”。
很久没有做Unity了,所以我的知识有点生锈。确保using System.Linq;
已在脚本中设置。
// Considering that "button" is the one on which you clicked.
// By definition, we have 2 Text children (for single Text, we
// could use button.GetComponentInChildren<Text>().color directly, as it returns single element.
var oreText = button.GetComponentsInChildren<Text>().FirstOrDefault(o => o.name == "Ore"); // Unity allows same naming...
// I had 2 Text components initially returned: Ore and Wood.
// Got the Ore text component with FirstOrDefault. Now check it really exists and set color.
if (oreText != null) // Long way to compare. For illustration.
{
oreText.color = Color.green;
}
// Also, if "Ore" button really exists, you can directly set it from "Single" method:
// button.GetComponentsInChildren<Text>().Single(o => o.name == "Ore").color = Color.green;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句