I can't draw() from script

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By null_digital
extends Control
class_name DrawThing

func _draw():
	var dest = Vector2(rect_position.x + 100, rect_position.y + 100)
	draw_line(rect_position, dest, Color.white, 5.0)

If I attach DrawThing to a Control in the scene, it’ll draw a line. But if I add it via script:

func _ready():
	var draw1 = DrawThing.new()
	draw1.rect_position = Vector2()

It won’t draw anything. What am I missing?
Having DrawThing extend Node2D solves the issue, but I really wanted to make it work with Control.

Have you checked if $NodeGrid/Control/Link is returning what you want?

Saitodepaula | 2019-12-05 12:20

What do you mean returning?

null_digital | 2019-12-05 12:27



to see what the engine returns. My guess was that it could be returning null.

But it looks you solved it, mark your own answer as the correct one, so other people know this question is solved.

Saitodepaula | 2019-12-05 13:32

_draw is a feature inherited from CanvasItem. Both Control and Node2D inherit CanvasItem, so it should have worked with extending a Control and using new… this is quite strange, maybe a bug even?

Zylann | 2019-12-05 13:58

Oh, NodeGrid/Control/Links wasn’t null for both cases.

null_digital | 2019-12-05 16:01

:bust_in_silhouette: Reply From: null_digital

I attached DrawThing to a scene and changed the code:

func _ready():
var draw1 = preload("res://src/draw_thing.tscn").instance()
draw1.rect_position = Vector2()

It works now. No idea why it won’t work with new(), though.

EDIT: created Inconsistent _draw() behavior between Control and Node2D · Issue #34119 · godotengine/godot · GitHub