+3 votes

Hello, I have been trying hard to change the color of a Label in a script, but I can't figure a way out...
Do you have a solution?

asked Mar 11, 2016 in Engine by Matt_UV (274 points)

1 Answer

+11 votes
Best answer

It is relatively simple, you should just use Control::add_color_override or Object::set

First of all, hover over the label before the color you want to change in the inspector. It would show a tooltip with info about the property name. In this case, it was custom_colors/font_color

To make it with add_color_override, take the right-most part of the property name. E.g. font_color. Then, use it like this:

add_color_override("font_color", Color(1,0,0))

Making it with set is just a bit easier (and a character shorter):

set("custom_colors/font_color", Color(1,0,0))
answered Mar 11, 2016 by Bojidar Marinov (1,554 points)
selected Mar 11, 2016 by Matt_UV

Thank you very much !
I didn't understand the 1st parameter of add_color_override(String name, Color color)nor the link between set()and the inspector.

I wouldn't have understood either, but a few days ago I was doing some Control-related PR, and saw it...

From the documentation alone, it's quite hard to know where this "custom_colors/font_color" comes from, and how you are supposed to figure it out.

Godot provides much of this information in hover-over tooltips. For instance, in this case, you have a Label node. In the inspector, you go to Control, and find Custom Colors, and under there Font Color, which is the property you want to manipulate in code. If you hover over the property name (not the input field, mind you), i.e. the Font Color text itself, you'll get a tooltip that says

Property: custom_colors/font_color

This covers the set(property: String, value: Variant) function.

If anyone has a good tip to know that for instance the custom_color/ prefix is covered by add_color_override(), I'd love to know. The documentation for Label will list the various properties under Theme Properties. For example, it shows font_color there. But this prefix of custom_color/ is not shown, and the link to add_color_override is as far as I can tell, is also not mentioned.

If working mostly in scripts, it seems to lead to the following scenario:

  1. Read documentation of Label
  2. See theme property of font_color, and decide to change it in code. But you need the full path of the property.
  3. Create the Node in the scene in order to see it in the inspector.
  4. Search through all the properties for something that looks like it matches font_color. Hover over and find the full path.
  5. Delete the node from the scene, and use the full property path in set.
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.