Generating image texture in Godot not working.

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Whirlatron

This code fails because the variable ‘image’ is Null, and therefore does not have the method fill. Since get_data() is supposed to return an Image object why does it return Null?

extends Node2D

export var WIDTH = 200
export var HEIGHT = 200

func _ready():
var sprite = get_node(“Sprite”)
sprite.texture = ImageTexture.new()
sprite.texture.create(WIDTH, HEIGHT, 5)
var image = sprite.texture.get_data()
image.fill(Color(0, 0, 0, 1))

:bust_in_silhouette: Reply From: Whirlatron

Figured it out; the code should look like this:

extends Node2D

export var WIDTH = 200
export var HEIGHT = 200

func _ready():
var sprite = get_node(“Sprite”)
var texture = ImageTexture.new()
var image = Image.new()
image.create(WIDTH, HEIGHT, false, 4)
image.fill(Color(0, 0, 0))
image.lock() # To enable drawing with set_pixel later
texture.create_from_image(image)