Mana
Mana

Reputation: 382

Trouble changing texture of a sprite using script in Godot

I have a Kinetic Body 2D in my game setup that I use to display different kinds of sprites in my dictionary as and when required. To do that, I used this code and it worked:

get_node("Pineapple").get_node("Display").set_texture(global_const.pineapple)

Where the variable pineapple was in this form in global_const.gd singleton script -

const pineapple = preload("res://Ingredients/Pineapple.png")

Later on, I decided to get rid of using "global_const" variables altogether as I built a dictionary for all the items I wanted to display. The new dictionary now looks like this -

const ingredients = [{iname="Pineapple", icon="res://Ingredients/pineapple.png"},
{iname="Cherry", icon="res://Ingredients/cherry.png"},
{iname="Banana", icon="res://Ingredients/banana.png"}]

I wanted to modify the code where I used set_texture and I did it this way -

for item in on_scene_ingredients: #this loops through all the instances of my Kinetic Body 2D.
#they have different values in "iname" to differentiate between each other
    for reference in dictionary.ingredients: #this checks all the items in my library
        if item.iname==reference.iname: #checks for common name to assign the desired icon
                item.get_node("Display").set_texture(reference.icon)

I tested if all the variables are correct and if there is any flaw with the logic, but there isn't. The only line that is causing the issue is this -

item.get_node("Display").set_texture(reference.icon)

Godot throws a runtime error - Invalid type in function 'set_texture' in base 'Sprite'. Cannot convert argument 1 from String to Object.

How do I fix this? Where am I going wrong?

Upvotes: 1

Views: 3557

Answers (1)

rcorre
rcorre

Reputation: 7238

Your dict is a mapping of String to String. reference.iname and reference.icon are both strings, so your code comes out to:

item.get_node("Display").set_texture("res://Ingredients/pineapple.png")

set_texture expects a Texture but you are passing a String. You need to load your texture before passing it to set_texture:

item.get_node("Display").set_texture(load(reference.icon))

Upvotes: 2

Related Questions