Changing loaded texture/sprite based on variables?

Godot Version

v4.5.stable.steam [876b29033]

Question

I’m very new to Godot (most familiar with Java, with a bit of Python knowledge, prior to this), so I’m not at all sure how to go about doing most things yet.

The project I want to work on revolves around cats with various appearances, however all will have the same underlying information/variables to them. So, make a Cat class with that information.
But I realized I don’t actually know how to make the actual visible appearance of a sprite/texture change to reflect the variables. For example, I want to be able to show a difference between long and short-haired cats, and every Cat would have a variable saying whether they’re long- or short-haired.
(The cats themselves will, hopefully, be randomly generated and differ from game to game, so I can’t just hard-code nodes to certain scenes with the information on which texture.)

So long question short, is there a way to use variables to determine which sprite/texture is displayed?

Make a variable that holds a reference to a texture.

1 Like

If you look at the inspector panel for a node (like, say, a sprite), it has a bunch of properties listed, some with values you’ve set. If you float the mouse over the name of one of those properties, it will give you a popup window with a description, and that description includes the name you use to access that property in script.

For your Sprite2D or whatever acting as your cat, there will be a texture property. You can set that directly in script, at runtime. You can set pretty much anything at runtime in script.

You might want to add a function to your cat node:

func setup_cat(img: Texture2D, nam: String) -> void:
    texture = img
    CatName = nam # Not "name" because Node already has a 'name' property...

You can then create a cat by doing something like:

    var cat = preload("res://cat.tscn").instantiate()
    # Set cat.position, anything else needed...
    cat.setup_cat(preload("res://cat_images/cat3.png"), "Tom")
    add_child(cat)
2 Likes