Changing Texture in Script - why doesn't this work?

Godot Version

4.3

Question

I am fairly new to Godot & am trying to build a log from component sprites. The base texture is a middle section & what I want is for the first component to be different. My code is as follows:
`const LOG_START = preload(“res://assets/Images/LogStart.png”)
@export var tile_offset_amount: Vector2 = Vector2(16,0)

func SetupLength() → void:
for item in range(1,4):
var sprite: Sprite2D = $Templates/Sprite2D.duplicate()
var shape: CollisionShape2D = $Templates/CollisionShape2D.duplicate()

	if item == 1:
		sprite.texture = LOG_START
	
	sprite.position = (item - 1) * tile_offset_amount
	shape.position = (item - 1) * tile_offset_amount
	
	$Area2D.add_child(sprite)
	$Area2D.add_child(shape)`

When I run it through the debugger I can see that the sprite changes however the log still only displays the base sprites. What am I missing?

1 Like

Might be a stupid question but, are your template sprites in the $Templates node set to visible = false? When you duplicate them, they maintain this property.

Also try checking your Remote to when you run to see if you can catch anything off?

2 Likes

No, visibility is on. Loooking at Remote the texture shows as the start log but on the game screen it displays the base log still.

Couple things I would try, Check the Z-index properties.

# When creating your sprites
if item == 1:
    sprite.texture = LOG_START
    sprite.z_index = 1  # Make sure it renders on top

Use queue_free() on the First sprites: If you’re keeping original sprites, try removing them first.

func SetupLength() -> void:
    for child in $Area2D.get_children():
        if child is Sprite2D:
            child.queue_free()
    
    # Then add your new ones
    for item in range(1, 4):

And lastly if nothing else works.

Force your textures to update. Sometimes explicitly setting the region can help.

if item == 1:
    sprite.texture = LOG_START
    sprite.region_enabled = false
    sprite.update()

That’s great, the Z index solved the issue. Should have thought of that myself! :frowning_face: Thanks for your help.

1 Like

Turns out I was a bit premature in thinking it was solved. Playing around with it a bit more the problem occurred on item == 1, any other value was fine. What I had to do was clear the texture in the inspector, create a constant for my base texture and then add an else: sprite.texture = LOG_MIDDLE to my if statement. If any body could explain why the problem exists I’d be very interested but at least it’s all working now.