+1 vote

I'm trying to programmatically crate texture, attached to Sprite node, and then write on it. I think this code should work but somehow it doesn't. Is it bug or am I doing it wrong?
Texture is displayed on screen as black. Using set_pixel instead of fill also doesn't work.

extends Node2D

func _ready():
    var imageTexture = ImageTexture.new()
    var image = Image.new() 
    image.create(256,256,false,Image.FORMAT_RGB8)       
    imageTexture.create_from_image(image)
    $Sprite.texture = imageTexture

    var data = $Sprite.texture.get_data()
    data.lock()
    data.fill(Color(1,0,0,1))
    data.unlock()
in Engine by (33 points)

2 Answers

0 votes

I can't test it right now but I think this should work.

var imageTexture = ImageTexture.new()
var image = Image.new()

image.create(256,256,false,Image.FORMAT_RGB8) 
image.fill(Color(1,0,0,1))

imageTexture.create_from_image(image)
$Sprite.texture = imageTexture
by (210 points)

Hi, thanks for answer. Yes this will work but I need to update texture later, not while creating. So I need to use get_data()

Ok. I believe you should switch data.lock() and data.unlock(). Because right now you lock it and then you try to set the color.
Also when you call $Sprite.texture.get_data() you will get an Image object. But it seems like you don't use it. So in order to get the image, manipulate it and set it back to the sprite you should do:

var data = $Sprite.texture.get_data()
data.unlock()
data.fill(Color(1,0,0,1))
data.lock()
var imageTexture = ImageTexture.new()
imageTexture.create_from_image(data)
$Sprite.texture = imageTexture
0 votes

get_data() is unnecessary. because you have already $Sprite.texture == imageTexture

func _ready():
    var imageTexture = ImageTexture.new()
    var image = Image.new()
    image.create(256,256,false,Image.FORMAT_RGB8)
    image.fill(Color(1,0,0,1))
    imageTexture.create_from_image(image)
    $Sprite.texture = imageTexture

    image.fill(Color(0,0,1,1))
    $Sprite.texture.set_data(image) #or imageTexture.set_data(image)

if it is still desired to do.

func _ready():
    var imageTexture = ImageTexture.new()
    var image = Image.new() 
    image.create(256,256,false,Image.FORMAT_RGB8)       
    imageTexture.create_from_image(image)
    $Sprite.texture = imageTexture

#read again and fill

    image = $Sprite.texture.get_data()
    image.fill(Color(1,0,0,1))
    $Sprite.texture.set_data(image)
by (154 points)
edited by
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.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.