Dynamically create TextureRect from script?

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

How do I go about creating a TextureRect from script?

I tried:

var image = Image.new().load("res://image.png")
var texture = ImageTexture.new().create_from_image(image) # <--
var TR = TextureRect.new()
TR.Texture = texture
add_child(TR)

But I keep on getting the error on ‘var texture’ of:

Invalid type in function 'create_from_image' in base 'ImageTexture'. Cannot convert argument 1 from int to Object.

Godot 3.0

It’s documented here: ImageTexture — Godot Engine (stable) documentation in English

var texture = ImageTexture.new()
var image = Image.new()
image.load("res://icon.png")
texture.create_from_image(image)
$Sprite.texture = texture

byrro | 2021-12-18 21:26

:bust_in_silhouette: Reply From: KoBeWi

That’s because you are chaining calls on assignment of your image and the end result is int (Image.load() returns int).

Try:

var image = Image.new()
image.load("res://image.png")

btw, this should work too:

var image = load("res://image.png")

Ok, changing it from Image.new().load, I instead just used load, which works. However, I still am un-sure about how to apply a texture to a new TextureRect?

DrewS | 2018-03-10 03:02

Well, there’s a mistake in your code. Should be TR.texture not TR.Texture.

KoBeWi | 2018-03-10 13:36

Hi! I’m pretty new with Godot and trying to achieve a similar thing.
I’d like to assign images programmatically to a TextureRect.

However,

var texture = ImageTexture.new()

gives me an error saying Condition '!texture->active' is true. returned: Ref<Image>().

when I try to replace it with

var texture = ImageTexture.create_from_image(image, 7)

it gives me an error saying Invalid call. Nonexistent function 'create_from_image' in base 'GDScriptNativeClass'.

here is my snippet:

var image = Image.new()
image.load("res://image.png")
var texture = ImageTexture.new()
texture.create_from_image(image, 7)
$TextureRect.texture = texture

Hoping for help, thanks a lot!

marierie | 2019-01-31 19:53