Attention | Topic was automatically imported from the old Question2Answer platform. | |
Asked By | kuchen | |
Old Version | Published before Godot 3 was released. |
Hello,
I try to create a label with some additional functionality by extending from the Label class:
# file: ColorLabel.gd
extends Label
var color
var count
var is_checked
func _init(clr, cnt):
color = clr
count = cnt
._init()
func _ready():
set_text(str(count))
add_color_override("font_color", color)
I create such aColorLabel
and add them to their parent node, but they do not show up on the screen:
const ColorLabel = preload("res://ColorLabel.gd")
# ...
var label = ColorLabel.new(count, color)
# set position, etc.
add_child(label)
When I instead use a usual Label
object, everyhing “works” as expected (i.e. the label shows up on screen, with the proper color, etc.):
var label = Label.new()
label.set_text(str(count))
label.add_color_override("font_color", color)
# set position, etc.
add_child(label)
Of course thats a workaround, but then I need to keep track of the color and the count in another way, so I would prefer the custom class.
Is it possible to derive from a control in such a way, and if yes, why does the custom label not show up?
I’m going to assume you’re doing the add_child() and such inside one of the entry functions for the class.
This all works fine for me. I had to change the init arguments around, in your example the Color is second, when it is supposed to be the first.
extends Node2D
const ColorLabel = preload("res://ColorLabel.gd")
func _ready():
var label = ColorLabel.new(Color(1,0,0), 100)
label.set_pos(Vector2(100,100))
add_child(label)
As an aside ._init()
won’t do anything. The internal functions with underscores are exceptions. They don’t make use of that syntax since they cannot be overridden. Each one you write in extended classes will always execute in a specific order. It can be tricky to work with so you will always want to test what they’re doing if you have multiple extended classes.
avencherus | 2017-10-27 09:24
Thank you avencherus! As embarrassing as it is, it seems the wrong argument order was the cause…
kuchen | 2017-10-27 09:51
I think @avencherus comment should be best answer for this question.
would you make it as answer?
and @kuchen can take it as best.
volzhs | 2017-10-27 12:20
@volzhs Will do. I recall seeing a convert to answer option once before, but its not available, so I will repost it.
@kuchen Glad that was it. Wasn’t sure since the other code was omitted.
avencherus | 2017-10-27 23:24