Set Texture of TextureRect in code

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

I’m trying to change the texture of my TextureRect when I click it. I was hoping that I could set all the frames in the animation, set it to 0 fps and just change to whichever frame I wanted, but I don’t see an option to do that. Alternatively, is there a way that I could just set the texture in code, e.g something like …

MyImage.Texture = "res://Graphics/image.png"

That doesn’t work but I’m trying to find some way to change the texture in code.

3 Likes
:bust_in_silhouette: Reply From: Zylann

Texture is a Texture property, you can’t assign text to it like you wrote.
You should load the texture from the path instead, because then load will return the proper texture:
MyImage.texture = load("res://Graphics/image.png")

Not working for me, I’m getting an error - Invalid set index ‘Texture’ (on base: ‘TextureRect (Kit.gd)’) with value of type ‘StreamTexture’.

Farflame | 2019-07-02 00:52

Sorry, it’s lowercase texture.

Zylann | 2019-07-02 00:55

Oh yeah, lol, it was that simple. Thanks, I’ve accepted this as the best answer.

Farflame | 2019-07-02 01:05

4 Likes

By example for Godot4 with C#

var texturePath= "res://textures/gui/maps/forest.png";
var texture2d = (Texture2D) GD.Load(texturePath);
MyTextureRect.Texture = texture2d;