Display programmatically set texture of sprite in editor

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By twilightends

I am loading my item database from a json-file. It basically is a dictionary with a dictionary for every item referenced by an item_id. E.g.:
var item_db = {
“item_id1”: {
“texture” : “res://asset/item/flower.png”,
},
“item_id2”: {
“texture” : “res://asset/item/chair.png”,
}
}

To set the texture of an item sprite I added the item_id as an exported variable. And if i want to add an item to my game I just set the exported variable to the corresponding id. E.g.:

func _ready():
if item_db.has(item_id):
var item = item_db.get(item_id)
$Sprite.texture = load(item.get(“texture”))

This works fine when the game is running. But if I add the item to my world in the godot editor I don’t see the texture just the default red cross. This is kind of obvious, because the texture is set in my _ready() func. But: It makes building my world in the godot editor very hard because I don’t see which items I added. I don’t see a difference between a chair and a flower, because the items are only displayed as the default red cross and not by the texture I set the item_id to.

Is there a solution to this?

:bust_in_silhouette: Reply From: njamster

Add the tool-keyword at the top of your script. This way your script will be executed in the editor as well. For further details, take a look at the documentation.

As the texture has to be only updated when the value of item_id changes, I would recommend defining a setter-function and move your _ready()-code there:

export var item_id setget item_id_set

func item_id_set(new_value):
	item_id = new_value
	if itemdb.has(item_id):
		var item = itemdb.get(item_id)
		$Sprite.texture = load(item.get("texture"))
	else:
		$Sprite.texture = null
:bust_in_silhouette: Reply From: Furegus

I believe that preloading all the files and making your script a tool is the only solution.