TextureRect and AtlasTexture

Godot Version

v4.3

Question

I created a TextureRect and assigned an AtlasTexture to it. My idea was to show a particular region from the Atlas depending on a value from the TextureRect. Something like:

@export var type: int = 0

It works as expected, but when I have several instances, if I change the region, it gets changed for all the instances. Is this behaviour normal? Could it be avoid it?

extends TextureRect
....
@export var type:Card = 0:
    set(value):
        type = value
        var tmp = Vector2(5,5)
        if type in _dict:
            tmp = _dict[type]
        set_region(tmp)


func set_region(rect) -> void:
    self.texture.region = Rect2(Vector2(1 * (rect[0] + 1) + (WIDTH + 2) * rect[0], 
                                        1 * (rect[1] + 1) + (HEIGHT + 1) * rect[1]), 
                                Vector2(WIDTH, HEIGHT))

AtlasTexure is a Resource and resources are shared by default, you need to create a unique copy of the atlas texture for every node:

extends TextureRect
....
@export var type:Card = 0:
    set(value):
        type = value
        var tmp = Vector2(5,5)
        if type in _dict:
            tmp = _dict[type]
        set_region(tmp)


func _ready() -> void:
	texture = texture.duplicate(true)


func set_region(rect) -> void:
    self.texture.region = Rect2(Vector2(1 * (rect[0] + 1) + (WIDTH + 2) * rect[0], 
                                        1 * (rect[1] + 1) + (HEIGHT + 1) * rect[1]), 
                                Vector2(WIDTH, HEIGHT))
1 Like

Or you can set it as Local to Scene = true in the Inspector.

1 Like

Understood. Thank you both.