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.
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".
Haven't done Unity for ages, so my knowledge is bit rusty. Make sure 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. 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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.