简体   繁体   English

如何更改按钮文本的颜色?

[英]How can I change the color of the text of a button?

I want to click a button and change its text's color and message properties.我想单击一个按钮并更改其文本的颜色和消息属性。

I got the button to change its color, but I need to change one of its text's colors.我得到了更改其颜色的按钮,但我需要更改其中一个文本的 colors。

private void TurnGreen(Button button)
{
    ColorBlock colors = button.colors;
    colors.normalColor = Color.green;
    button.colors = colors;
}

The above code changed the button's color which I liked, but I would rather change the button's text.上面的代码改变了我喜欢的按钮颜色,但我宁愿改变按钮的文本。 Note however that my button has two text-childs.但是请注意,我的按钮有两个文本子项。 The text I want to change has a name of "Ore".我要更改的文本名称为“Ore”。

Haven't done Unity for ages, so my knowledge is bit rusty.很久没有做过Unity了,所以我的知识有点生疏。 Make sure using System.Linq;确保using System.Linq; is set in your script.在您的脚本中设置。

        // 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;

在此处输入图像描述

A better way to do this might be to identify the text component in question from the editor (assuming your button is a Prefab), rather than iterating through the components via Linq.更好的方法可能是从编辑器中识别有问题的文本组件(假设您的按钮是预制件),而不是通过 Linq 遍历组件。 If you do it that way, it's scales a little better if you want to use that type of behavior on other components/buttons but don't want to have to change the Linq search text each time.如果你这样做,如果你想在其他组件/按钮上使用这种类型的行为,但又不想每次都更改 Linq 搜索文本,它的扩展性会更好一些。

To do this, create a new field like this:为此,请创建一个新字段,如下所示:

public Text textToChange;

Then drag the component in question form your button into your component script from the editor, then in code do this:然后将有问题的组件从您的按钮拖到编辑器中的组件脚本中,然后在代码中执行以下操作:

textToChange?.color = Color.green;

And then boom, you're done...the '?.'然后繁荣,你完成了......'?。 also checks for null for you without the if block.在没有 if 块的情况下,还会为您检查 null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM