Drawing is only allowed inside [...] for no apparent reason

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By dbiton
:warning: Old Version Published before Godot 3 was released.

I get the following error “Drawing is only allowed inside NOTIFICATION_DRAW, _draw() function or ‘draw’.”, on the code attached bellow.

I don’t understand the reason for the error, as the function is called from inside a _draw() function.

extends Node

var cur_width = 0
var x = 0
var y = 0
var done
var pixels_per_second
var time_fill_bar = 0.5 #seconds
var width
var coe

onready var refrence_frame = get_parent()

func _ready():
	var health = get_node("/root/Root/Samurai").get("health")
	width = refrence_frame.get_size().x
	coe = float(width)/health
	pixels_per_second = float(health)/float(time_fill_bar)
	set_process(true)

func _process(delta):
	if !done:
		if x < width:
			x += pixels_per_second*delta
		if x >= width:
			done = true
			x = width
	else:
		x = get_node("/root/Root/Samurai").get("health")*coe
	_draw()
	
func _draw():
	update()
	var rect = Rect2(0,0,x,refrence_frame.get_size().y)
	var color = Color(1,0,0,1)
	draw_rect(rect,color)

Is this a bug? should I report it to the GitHub?

:bust_in_silhouette: Reply From: eons

You’re doing it the other way around, call update in _process instead of draw, and don’t call update inside _draw.

Look at docs for more detail:

extends Node

var cur_width = 0
var x = 0
var y = 0
var done
var pixels_per_second
var time_fill_bar = 0.5 #seconds
var width
var coe

onready var refrence_frame = get_parent()

func _ready():
    var health = get_node("/root/Root/Samurai").get("health")
    width = refrence_frame.get_size().x
    coe = float(width)/health
    pixels_per_second = float(health)/float(time_fill_bar)
    set_process(true)

func _process(delta):
    if !done:
        if x < width:
            x += pixels_per_second*delta
        if x >= width:
            done = true
            x = width
    else:
        x = get_node("/root/Root/Samurai").get("health")*coe
    update()

func _draw():
    var rect = Rect2(0,0,x,refrence_frame.get_size().y)
    var color = Color(1,0,0,1)
    draw_rect(rect,color)

mateusak | 2017-04-20 00:34