Lynn Len
Lynn Len

Reputation: 111

How do I change sprites in scripts?

I'm trying to make a dating sim as a easy first game programming-wise. I don't know how to change the character sprites inside the scripts.

character_sprite.gd

extends Sprite

var char_tex = load("res://Sprites/Lu2.png") 

func _ready():
    set_texture(char_tex)

func _input(event):
    if event is InputEventMouseButton:
        char_tex = load("res://Sprites/Lu1.png")
        update()

Upvotes: 8

Views: 25216

Answers (1)

skrx
skrx

Reputation: 20488

Just set the texture property to the desired texture. You could also preload the textures and then just switch them instead of loading them again.

extends Sprite

var char_tex = load("res://Sprites/Lu2.png") 

func _ready():
    set_process_input(true)
    texture = char_tex

func _input(event):
    if event is InputEventMouseButton:
        texture = load("res://Sprites/Lu1.png")

The problem in your example was that you only assigned a new image to the char_tex variable, but that doesn't change the texture of the sprite. The texture will still refer to the previous image until you assign the new one with texture = or set_texture. Gdscript is relatively similar to Python in this regard, so I recommend taking a look at Ned Batchelder's talk Facts and myths about Python names and Values.

Upvotes: 6

Related Questions