簡體   English   中英

如何更改按鈕文本的顏色?

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

我想單擊一個按鈕並更改其文本的顏色和消息屬性。

我得到了更改其顏色的按鈕,但我需要更改其中一個文本的 colors。

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

上面的代碼改變了我喜歡的按鈕顏色,但我寧願改變按鈕的文本。 但是請注意,我的按鈕有兩個文本子項。 我要更改的文本名稱為“Ore”。

很久沒有做過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;

在此處輸入圖像描述

更好的方法可能是從編輯器中識別有問題的文本組件(假設您的按鈕是預制件),而不是通過 Linq 遍歷組件。 如果你這樣做,如果你想在其他組件/按鈕上使用這種類型的行為,但又不想每次都更改 Linq 搜索文本,它的擴展性會更好一些。

為此,請創建一個新字段,如下所示:

public Text textToChange;

然后將有問題的組件從您的按鈕拖到編輯器中的組件腳本中,然后在代碼中執行以下操作:

textToChange?.color = Color.green;

然后繁榮,你完成了......'?。 在沒有 if 塊的情況下,還會為您檢查 null。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM